babylon.max.js 4.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. var BABYLON;
  839. (function (BABYLON) {
  840. var KeyboardEventTypes = /** @class */ (function () {
  841. function KeyboardEventTypes() {
  842. }
  843. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  844. get: function () {
  845. return KeyboardEventTypes._KEYDOWN;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  851. get: function () {
  852. return KeyboardEventTypes._KEYUP;
  853. },
  854. enumerable: true,
  855. configurable: true
  856. });
  857. KeyboardEventTypes._KEYDOWN = 0x01;
  858. KeyboardEventTypes._KEYUP = 0x02;
  859. return KeyboardEventTypes;
  860. }());
  861. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  862. var KeyboardInfo = /** @class */ (function () {
  863. function KeyboardInfo(type, event) {
  864. this.type = type;
  865. this.event = event;
  866. }
  867. return KeyboardInfo;
  868. }());
  869. BABYLON.KeyboardInfo = KeyboardInfo;
  870. /**
  871. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  872. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  873. */
  874. var KeyboardInfoPre = /** @class */ (function (_super) {
  875. __extends(KeyboardInfoPre, _super);
  876. function KeyboardInfoPre(type, event) {
  877. var _this = _super.call(this, type, event) || this;
  878. _this.skipOnPointerObservable = false;
  879. return _this;
  880. }
  881. return KeyboardInfoPre;
  882. }(KeyboardInfo));
  883. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  884. })(BABYLON || (BABYLON = {}));
  885. //# sourceMappingURL=babylon.keyboardEvents.js.map
  886. var BABYLON;
  887. (function (BABYLON) {
  888. var PointerEventTypes = /** @class */ (function () {
  889. function PointerEventTypes() {
  890. }
  891. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  892. get: function () {
  893. return PointerEventTypes._POINTERDOWN;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  899. get: function () {
  900. return PointerEventTypes._POINTERUP;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  906. get: function () {
  907. return PointerEventTypes._POINTERMOVE;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  913. get: function () {
  914. return PointerEventTypes._POINTERWHEEL;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  920. get: function () {
  921. return PointerEventTypes._POINTERPICK;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  927. get: function () {
  928. return PointerEventTypes._POINTERTAP;
  929. },
  930. enumerable: true,
  931. configurable: true
  932. });
  933. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  934. get: function () {
  935. return PointerEventTypes._POINTERDOUBLETAP;
  936. },
  937. enumerable: true,
  938. configurable: true
  939. });
  940. PointerEventTypes._POINTERDOWN = 0x01;
  941. PointerEventTypes._POINTERUP = 0x02;
  942. PointerEventTypes._POINTERMOVE = 0x04;
  943. PointerEventTypes._POINTERWHEEL = 0x08;
  944. PointerEventTypes._POINTERPICK = 0x10;
  945. PointerEventTypes._POINTERTAP = 0x20;
  946. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  947. return PointerEventTypes;
  948. }());
  949. BABYLON.PointerEventTypes = PointerEventTypes;
  950. var PointerInfoBase = /** @class */ (function () {
  951. function PointerInfoBase(type, event) {
  952. this.type = type;
  953. this.event = event;
  954. }
  955. return PointerInfoBase;
  956. }());
  957. BABYLON.PointerInfoBase = PointerInfoBase;
  958. /**
  959. * This class is used to store pointer related info for the onPrePointerObservable event.
  960. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  961. */
  962. var PointerInfoPre = /** @class */ (function (_super) {
  963. __extends(PointerInfoPre, _super);
  964. function PointerInfoPre(type, event, localX, localY) {
  965. var _this = _super.call(this, type, event) || this;
  966. _this.skipOnPointerObservable = false;
  967. _this.localPosition = new BABYLON.Vector2(localX, localY);
  968. return _this;
  969. }
  970. return PointerInfoPre;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfoPre = PointerInfoPre;
  973. /**
  974. * This type contains all the data related to a pointer event in Babylon.js.
  975. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  976. */
  977. var PointerInfo = /** @class */ (function (_super) {
  978. __extends(PointerInfo, _super);
  979. function PointerInfo(type, event, pickInfo) {
  980. var _this = _super.call(this, type, event) || this;
  981. _this.pickInfo = pickInfo;
  982. return _this;
  983. }
  984. return PointerInfo;
  985. }(PointerInfoBase));
  986. BABYLON.PointerInfo = PointerInfo;
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.pointerEvents.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. BABYLON.ToGammaSpace = 1 / 2.2;
  992. BABYLON.ToLinearSpace = 2.2;
  993. BABYLON.Epsilon = 0.001;
  994. var Color3 = /** @class */ (function () {
  995. /**
  996. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  997. */
  998. function Color3(r, g, b) {
  999. if (r === void 0) { r = 0; }
  1000. if (g === void 0) { g = 0; }
  1001. if (b === void 0) { b = 0; }
  1002. this.r = r;
  1003. this.g = g;
  1004. this.b = b;
  1005. }
  1006. /**
  1007. * Returns a string with the Color3 current values.
  1008. */
  1009. Color3.prototype.toString = function () {
  1010. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1011. };
  1012. /**
  1013. * Returns the string "Color3".
  1014. */
  1015. Color3.prototype.getClassName = function () {
  1016. return "Color3";
  1017. };
  1018. /**
  1019. * Returns the Color3 hash code.
  1020. */
  1021. Color3.prototype.getHashCode = function () {
  1022. var hash = this.r || 0;
  1023. hash = (hash * 397) ^ (this.g || 0);
  1024. hash = (hash * 397) ^ (this.b || 0);
  1025. return hash;
  1026. };
  1027. // Operators
  1028. /**
  1029. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1030. * Returns the Color3.
  1031. */
  1032. Color3.prototype.toArray = function (array, index) {
  1033. if (index === undefined) {
  1034. index = 0;
  1035. }
  1036. array[index] = this.r;
  1037. array[index + 1] = this.g;
  1038. array[index + 2] = this.b;
  1039. return this;
  1040. };
  1041. /**
  1042. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1043. */
  1044. Color3.prototype.toColor4 = function (alpha) {
  1045. if (alpha === void 0) { alpha = 1; }
  1046. return new Color4(this.r, this.g, this.b, alpha);
  1047. };
  1048. /**
  1049. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1050. */
  1051. Color3.prototype.asArray = function () {
  1052. var result = new Array();
  1053. this.toArray(result, 0);
  1054. return result;
  1055. };
  1056. /**
  1057. * Returns the luminance value (float).
  1058. */
  1059. Color3.prototype.toLuminance = function () {
  1060. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1061. };
  1062. /**
  1063. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1064. * Returns this new object.
  1065. */
  1066. Color3.prototype.multiply = function (otherColor) {
  1067. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1068. };
  1069. /**
  1070. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1071. * Returns the current Color3.
  1072. */
  1073. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1074. result.r = this.r * otherColor.r;
  1075. result.g = this.g * otherColor.g;
  1076. result.b = this.b * otherColor.b;
  1077. return this;
  1078. };
  1079. /**
  1080. * Boolean : True if the rgb values are equal to the passed ones.
  1081. */
  1082. Color3.prototype.equals = function (otherColor) {
  1083. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1084. };
  1085. /**
  1086. * Boolean : True if the rgb values are equal to the passed ones.
  1087. */
  1088. Color3.prototype.equalsFloats = function (r, g, b) {
  1089. return this.r === r && this.g === g && this.b === b;
  1090. };
  1091. /**
  1092. * Multiplies in place each rgb value by scale.
  1093. * Returns the updated Color3.
  1094. */
  1095. Color3.prototype.scale = function (scale) {
  1096. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1097. };
  1098. /**
  1099. * Multiplies the rgb values by scale and stores the result into "result".
  1100. * Returns the unmodified current Color3.
  1101. */
  1102. Color3.prototype.scaleToRef = function (scale, result) {
  1103. result.r = this.r * scale;
  1104. result.g = this.g * scale;
  1105. result.b = this.b * scale;
  1106. return this;
  1107. };
  1108. /**
  1109. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1110. */
  1111. Color3.prototype.add = function (otherColor) {
  1112. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1113. };
  1114. /**
  1115. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1116. * Returns the unmodified current Color3.
  1117. */
  1118. Color3.prototype.addToRef = function (otherColor, result) {
  1119. result.r = this.r + otherColor.r;
  1120. result.g = this.g + otherColor.g;
  1121. result.b = this.b + otherColor.b;
  1122. return this;
  1123. };
  1124. /**
  1125. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1126. */
  1127. Color3.prototype.subtract = function (otherColor) {
  1128. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1129. };
  1130. /**
  1131. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1132. * Returns the unmodified current Color3.
  1133. */
  1134. Color3.prototype.subtractToRef = function (otherColor, result) {
  1135. result.r = this.r - otherColor.r;
  1136. result.g = this.g - otherColor.g;
  1137. result.b = this.b - otherColor.b;
  1138. return this;
  1139. };
  1140. /**
  1141. * Returns a new Color3 copied the current one.
  1142. */
  1143. Color3.prototype.clone = function () {
  1144. return new Color3(this.r, this.g, this.b);
  1145. };
  1146. /**
  1147. * Copies the rgb values from the source in the current Color3.
  1148. * Returns the updated Color3.
  1149. */
  1150. Color3.prototype.copyFrom = function (source) {
  1151. this.r = source.r;
  1152. this.g = source.g;
  1153. this.b = source.b;
  1154. return this;
  1155. };
  1156. /**
  1157. * Updates the Color3 rgb values from the passed floats.
  1158. * Returns the Color3.
  1159. */
  1160. Color3.prototype.copyFromFloats = function (r, g, b) {
  1161. this.r = r;
  1162. this.g = g;
  1163. this.b = b;
  1164. return this;
  1165. };
  1166. /**
  1167. * Updates the Color3 rgb values from the passed floats.
  1168. * Returns the Color3.
  1169. */
  1170. Color3.prototype.set = function (r, g, b) {
  1171. return this.copyFromFloats(r, g, b);
  1172. };
  1173. /**
  1174. * Returns the Color3 hexadecimal code as a string.
  1175. */
  1176. Color3.prototype.toHexString = function () {
  1177. var intR = (this.r * 255) | 0;
  1178. var intG = (this.g * 255) | 0;
  1179. var intB = (this.b * 255) | 0;
  1180. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1181. };
  1182. /**
  1183. * Returns a new Color3 converted to linear space.
  1184. */
  1185. Color3.prototype.toLinearSpace = function () {
  1186. var convertedColor = new Color3();
  1187. this.toLinearSpaceToRef(convertedColor);
  1188. return convertedColor;
  1189. };
  1190. /**
  1191. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1192. * Returns the unmodified Color3.
  1193. */
  1194. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1195. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1196. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1197. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Color3 converted to gamma space.
  1202. */
  1203. Color3.prototype.toGammaSpace = function () {
  1204. var convertedColor = new Color3();
  1205. this.toGammaSpaceToRef(convertedColor);
  1206. return convertedColor;
  1207. };
  1208. /**
  1209. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1210. * Returns the unmodified Color3.
  1211. */
  1212. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1213. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1214. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1215. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1216. return this;
  1217. };
  1218. // Statics
  1219. /**
  1220. * Creates a new Color3 from the string containing valid hexadecimal values.
  1221. */
  1222. Color3.FromHexString = function (hex) {
  1223. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1224. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1225. return new Color3(0, 0, 0);
  1226. }
  1227. var r = parseInt(hex.substring(1, 3), 16);
  1228. var g = parseInt(hex.substring(3, 5), 16);
  1229. var b = parseInt(hex.substring(5, 7), 16);
  1230. return Color3.FromInts(r, g, b);
  1231. };
  1232. /**
  1233. * Creates a new Vector3 from the startind index of the passed array.
  1234. */
  1235. Color3.FromArray = function (array, offset) {
  1236. if (offset === void 0) { offset = 0; }
  1237. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1238. };
  1239. /**
  1240. * Creates a new Color3 from integer values ( < 256).
  1241. */
  1242. Color3.FromInts = function (r, g, b) {
  1243. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1244. };
  1245. /**
  1246. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1247. */
  1248. Color3.Lerp = function (start, end, amount) {
  1249. var r = start.r + ((end.r - start.r) * amount);
  1250. var g = start.g + ((end.g - start.g) * amount);
  1251. var b = start.b + ((end.b - start.b) * amount);
  1252. return new Color3(r, g, b);
  1253. };
  1254. Color3.Red = function () { return new Color3(1, 0, 0); };
  1255. Color3.Green = function () { return new Color3(0, 1, 0); };
  1256. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1257. Color3.Black = function () { return new Color3(0, 0, 0); };
  1258. Color3.White = function () { return new Color3(1, 1, 1); };
  1259. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1260. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1261. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1262. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1263. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1264. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1265. return Color3;
  1266. }());
  1267. BABYLON.Color3 = Color3;
  1268. var Color4 = /** @class */ (function () {
  1269. /**
  1270. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1271. */
  1272. function Color4(r, g, b, a) {
  1273. if (r === void 0) { r = 0; }
  1274. if (g === void 0) { g = 0; }
  1275. if (b === void 0) { b = 0; }
  1276. if (a === void 0) { a = 1; }
  1277. this.r = r;
  1278. this.g = g;
  1279. this.b = b;
  1280. this.a = a;
  1281. }
  1282. // Operators
  1283. /**
  1284. * Adds in place the passed Color4 values to the current Color4.
  1285. * Returns the updated Color4.
  1286. */
  1287. Color4.prototype.addInPlace = function (right) {
  1288. this.r += right.r;
  1289. this.g += right.g;
  1290. this.b += right.b;
  1291. this.a += right.a;
  1292. return this;
  1293. };
  1294. /**
  1295. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1296. */
  1297. Color4.prototype.asArray = function () {
  1298. var result = new Array();
  1299. this.toArray(result, 0);
  1300. return result;
  1301. };
  1302. /**
  1303. * Stores from the starting index in the passed array the Color4 successive values.
  1304. * Returns the Color4.
  1305. */
  1306. Color4.prototype.toArray = function (array, index) {
  1307. if (index === undefined) {
  1308. index = 0;
  1309. }
  1310. array[index] = this.r;
  1311. array[index + 1] = this.g;
  1312. array[index + 2] = this.b;
  1313. array[index + 3] = this.a;
  1314. return this;
  1315. };
  1316. /**
  1317. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1318. */
  1319. Color4.prototype.add = function (right) {
  1320. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1321. };
  1322. /**
  1323. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1324. */
  1325. Color4.prototype.subtract = function (right) {
  1326. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1327. };
  1328. /**
  1329. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1330. * Returns the Color4.
  1331. */
  1332. Color4.prototype.subtractToRef = function (right, result) {
  1333. result.r = this.r - right.r;
  1334. result.g = this.g - right.g;
  1335. result.b = this.b - right.b;
  1336. result.a = this.a - right.a;
  1337. return this;
  1338. };
  1339. /**
  1340. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1341. */
  1342. Color4.prototype.scale = function (scale) {
  1343. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1344. };
  1345. /**
  1346. * Multiplies the current Color4 values by scale and stores the result in "result".
  1347. * Returns the Color4.
  1348. */
  1349. Color4.prototype.scaleToRef = function (scale, result) {
  1350. result.r = this.r * scale;
  1351. result.g = this.g * scale;
  1352. result.b = this.b * scale;
  1353. result.a = this.a * scale;
  1354. return this;
  1355. };
  1356. /**
  1357. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1358. * @param color The Color4 (RGBA) value to multiply by
  1359. * @returns A new Color4.
  1360. */
  1361. Color4.prototype.multiply = function (color) {
  1362. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1363. };
  1364. /**
  1365. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1366. * @param color The Color4 (RGBA) value to multiply by
  1367. * @param result The Color4 (RGBA) to fill the result in
  1368. * @returns the result Color4.
  1369. */
  1370. Color4.prototype.multiplyToRef = function (color, result) {
  1371. result.r = this.r * color.r;
  1372. result.g = this.g * color.g;
  1373. result.b = this.b * color.b;
  1374. result.a = this.a * color.a;
  1375. return result;
  1376. };
  1377. /**
  1378. * Returns a string with the Color4 values.
  1379. */
  1380. Color4.prototype.toString = function () {
  1381. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1382. };
  1383. /**
  1384. * Returns the string "Color4"
  1385. */
  1386. Color4.prototype.getClassName = function () {
  1387. return "Color4";
  1388. };
  1389. /**
  1390. * Return the Color4 hash code as a number.
  1391. */
  1392. Color4.prototype.getHashCode = function () {
  1393. var hash = this.r || 0;
  1394. hash = (hash * 397) ^ (this.g || 0);
  1395. hash = (hash * 397) ^ (this.b || 0);
  1396. hash = (hash * 397) ^ (this.a || 0);
  1397. return hash;
  1398. };
  1399. /**
  1400. * Creates a new Color4 copied from the current one.
  1401. */
  1402. Color4.prototype.clone = function () {
  1403. return new Color4(this.r, this.g, this.b, this.a);
  1404. };
  1405. /**
  1406. * Copies the passed Color4 values into the current one.
  1407. * Returns the updated Color4.
  1408. */
  1409. Color4.prototype.copyFrom = function (source) {
  1410. this.r = source.r;
  1411. this.g = source.g;
  1412. this.b = source.b;
  1413. this.a = source.a;
  1414. return this;
  1415. };
  1416. /**
  1417. * Copies the passed float values into the current one.
  1418. * Returns the updated Color4.
  1419. */
  1420. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1421. this.r = r;
  1422. this.g = g;
  1423. this.b = b;
  1424. this.a = a;
  1425. return this;
  1426. };
  1427. /**
  1428. * Copies the passed float values into the current one.
  1429. * Returns the updated Color4.
  1430. */
  1431. Color4.prototype.set = function (r, g, b, a) {
  1432. return this.copyFromFloats(r, g, b, a);
  1433. };
  1434. /**
  1435. * Returns a string containing the hexadecimal Color4 code.
  1436. */
  1437. Color4.prototype.toHexString = function () {
  1438. var intR = (this.r * 255) | 0;
  1439. var intG = (this.g * 255) | 0;
  1440. var intB = (this.b * 255) | 0;
  1441. var intA = (this.a * 255) | 0;
  1442. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1443. };
  1444. /**
  1445. * Returns a new Color4 converted to linear space.
  1446. */
  1447. Color4.prototype.toLinearSpace = function () {
  1448. var convertedColor = new Color4();
  1449. this.toLinearSpaceToRef(convertedColor);
  1450. return convertedColor;
  1451. };
  1452. /**
  1453. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1454. * Returns the unmodified Color4.
  1455. */
  1456. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1457. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1458. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1459. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1460. convertedColor.a = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new Color4 converted to gamma space.
  1465. */
  1466. Color4.prototype.toGammaSpace = function () {
  1467. var convertedColor = new Color4();
  1468. this.toGammaSpaceToRef(convertedColor);
  1469. return convertedColor;
  1470. };
  1471. /**
  1472. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1473. * Returns the unmodified Color4.
  1474. */
  1475. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1476. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1477. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1478. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1479. convertedColor.a = this.a;
  1480. return this;
  1481. };
  1482. // Statics
  1483. /**
  1484. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1485. */
  1486. Color4.FromHexString = function (hex) {
  1487. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1488. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1489. return new Color4(0.0, 0.0, 0.0, 0.0);
  1490. }
  1491. var r = parseInt(hex.substring(1, 3), 16);
  1492. var g = parseInt(hex.substring(3, 5), 16);
  1493. var b = parseInt(hex.substring(5, 7), 16);
  1494. var a = parseInt(hex.substring(7, 9), 16);
  1495. return Color4.FromInts(r, g, b, a);
  1496. };
  1497. /**
  1498. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1499. */
  1500. Color4.Lerp = function (left, right, amount) {
  1501. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1502. Color4.LerpToRef(left, right, amount, result);
  1503. return result;
  1504. };
  1505. /**
  1506. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1507. */
  1508. Color4.LerpToRef = function (left, right, amount, result) {
  1509. result.r = left.r + (right.r - left.r) * amount;
  1510. result.g = left.g + (right.g - left.g) * amount;
  1511. result.b = left.b + (right.b - left.b) * amount;
  1512. result.a = left.a + (right.a - left.a) * amount;
  1513. };
  1514. /**
  1515. * Creates a new Color4 from the starting index element of the passed array.
  1516. */
  1517. Color4.FromArray = function (array, offset) {
  1518. if (offset === void 0) { offset = 0; }
  1519. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1520. };
  1521. /**
  1522. * Creates a new Color4 from the passed integers ( < 256 ).
  1523. */
  1524. Color4.FromInts = function (r, g, b, a) {
  1525. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1526. };
  1527. Color4.CheckColors4 = function (colors, count) {
  1528. // Check if color3 was used
  1529. if (colors.length === count * 3) {
  1530. var colors4 = [];
  1531. for (var index = 0; index < colors.length; index += 3) {
  1532. var newIndex = (index / 3) * 4;
  1533. colors4[newIndex] = colors[index];
  1534. colors4[newIndex + 1] = colors[index + 1];
  1535. colors4[newIndex + 2] = colors[index + 2];
  1536. colors4[newIndex + 3] = 1.0;
  1537. }
  1538. return colors4;
  1539. }
  1540. return colors;
  1541. };
  1542. return Color4;
  1543. }());
  1544. BABYLON.Color4 = Color4;
  1545. var Vector2 = /** @class */ (function () {
  1546. /**
  1547. * Creates a new Vector2 from the passed x and y coordinates.
  1548. */
  1549. function Vector2(x, y) {
  1550. this.x = x;
  1551. this.y = y;
  1552. }
  1553. /**
  1554. * Returns a string with the Vector2 coordinates.
  1555. */
  1556. Vector2.prototype.toString = function () {
  1557. return "{X: " + this.x + " Y:" + this.y + "}";
  1558. };
  1559. /**
  1560. * Returns the string "Vector2"
  1561. */
  1562. Vector2.prototype.getClassName = function () {
  1563. return "Vector2";
  1564. };
  1565. /**
  1566. * Returns the Vector2 hash code as a number.
  1567. */
  1568. Vector2.prototype.getHashCode = function () {
  1569. var hash = this.x || 0;
  1570. hash = (hash * 397) ^ (this.y || 0);
  1571. return hash;
  1572. };
  1573. // Operators
  1574. /**
  1575. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1576. * Returns the Vector2.
  1577. */
  1578. Vector2.prototype.toArray = function (array, index) {
  1579. if (index === void 0) { index = 0; }
  1580. array[index] = this.x;
  1581. array[index + 1] = this.y;
  1582. return this;
  1583. };
  1584. /**
  1585. * Returns a new array with 2 elements : the Vector2 coordinates.
  1586. */
  1587. Vector2.prototype.asArray = function () {
  1588. var result = new Array();
  1589. this.toArray(result, 0);
  1590. return result;
  1591. };
  1592. /**
  1593. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1594. * Returns the updated Vector2.
  1595. */
  1596. Vector2.prototype.copyFrom = function (source) {
  1597. this.x = source.x;
  1598. this.y = source.y;
  1599. return this;
  1600. };
  1601. /**
  1602. * Sets the Vector2 coordinates with the passed floats.
  1603. * Returns the updated Vector2.
  1604. */
  1605. Vector2.prototype.copyFromFloats = function (x, y) {
  1606. this.x = x;
  1607. this.y = y;
  1608. return this;
  1609. };
  1610. /**
  1611. * Sets the Vector2 coordinates with the passed floats.
  1612. * Returns the updated Vector2.
  1613. */
  1614. Vector2.prototype.set = function (x, y) {
  1615. return this.copyFromFloats(x, y);
  1616. };
  1617. /**
  1618. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1619. */
  1620. Vector2.prototype.add = function (otherVector) {
  1621. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1622. };
  1623. /**
  1624. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1625. * Returns the Vector2.
  1626. */
  1627. Vector2.prototype.addToRef = function (otherVector, result) {
  1628. result.x = this.x + otherVector.x;
  1629. result.y = this.y + otherVector.y;
  1630. return this;
  1631. };
  1632. /**
  1633. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1634. * Returns the updated Vector2.
  1635. */
  1636. Vector2.prototype.addInPlace = function (otherVector) {
  1637. this.x += otherVector.x;
  1638. this.y += otherVector.y;
  1639. return this;
  1640. };
  1641. /**
  1642. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1643. */
  1644. Vector2.prototype.addVector3 = function (otherVector) {
  1645. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1646. };
  1647. /**
  1648. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1649. */
  1650. Vector2.prototype.subtract = function (otherVector) {
  1651. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1652. };
  1653. /**
  1654. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1655. * Returns the Vector2.
  1656. */
  1657. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1658. result.x = this.x - otherVector.x;
  1659. result.y = this.y - otherVector.y;
  1660. return this;
  1661. };
  1662. /**
  1663. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1664. * Returns the updated Vector2.
  1665. */
  1666. Vector2.prototype.subtractInPlace = function (otherVector) {
  1667. this.x -= otherVector.x;
  1668. this.y -= otherVector.y;
  1669. return this;
  1670. };
  1671. /**
  1672. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1673. * Returns the updated Vector2.
  1674. */
  1675. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1676. this.x *= otherVector.x;
  1677. this.y *= otherVector.y;
  1678. return this;
  1679. };
  1680. /**
  1681. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1682. */
  1683. Vector2.prototype.multiply = function (otherVector) {
  1684. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1685. };
  1686. /**
  1687. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1688. * Returns the Vector2.
  1689. */
  1690. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1691. result.x = this.x * otherVector.x;
  1692. result.y = this.y * otherVector.y;
  1693. return this;
  1694. };
  1695. /**
  1696. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1697. */
  1698. Vector2.prototype.multiplyByFloats = function (x, y) {
  1699. return new Vector2(this.x * x, this.y * y);
  1700. };
  1701. /**
  1702. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1703. */
  1704. Vector2.prototype.divide = function (otherVector) {
  1705. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1706. };
  1707. /**
  1708. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1709. * Returns the Vector2.
  1710. */
  1711. Vector2.prototype.divideToRef = function (otherVector, result) {
  1712. result.x = this.x / otherVector.x;
  1713. result.y = this.y / otherVector.y;
  1714. return this;
  1715. };
  1716. /**
  1717. * Divides the current Vector3 coordinates by the passed ones.
  1718. * Returns the updated Vector3.
  1719. */
  1720. Vector2.prototype.divideInPlace = function (otherVector) {
  1721. return this.divideToRef(otherVector, this);
  1722. };
  1723. /**
  1724. * Returns a new Vector2 with current Vector2 negated coordinates.
  1725. */
  1726. Vector2.prototype.negate = function () {
  1727. return new Vector2(-this.x, -this.y);
  1728. };
  1729. /**
  1730. * Multiply the Vector2 coordinates by scale.
  1731. * Returns the updated Vector2.
  1732. */
  1733. Vector2.prototype.scaleInPlace = function (scale) {
  1734. this.x *= scale;
  1735. this.y *= scale;
  1736. return this;
  1737. };
  1738. /**
  1739. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1740. */
  1741. Vector2.prototype.scale = function (scale) {
  1742. return new Vector2(this.x * scale, this.y * scale);
  1743. };
  1744. /**
  1745. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1746. */
  1747. Vector2.prototype.equals = function (otherVector) {
  1748. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1749. };
  1750. /**
  1751. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1752. */
  1753. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1754. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1755. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1756. };
  1757. // Properties
  1758. /**
  1759. * Returns the vector length (float).
  1760. */
  1761. Vector2.prototype.length = function () {
  1762. return Math.sqrt(this.x * this.x + this.y * this.y);
  1763. };
  1764. /**
  1765. * Returns the vector squared length (float);
  1766. */
  1767. Vector2.prototype.lengthSquared = function () {
  1768. return (this.x * this.x + this.y * this.y);
  1769. };
  1770. // Methods
  1771. /**
  1772. * Normalize the vector.
  1773. * Returns the updated Vector2.
  1774. */
  1775. Vector2.prototype.normalize = function () {
  1776. var len = this.length();
  1777. if (len === 0)
  1778. return this;
  1779. var num = 1.0 / len;
  1780. this.x *= num;
  1781. this.y *= num;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector2 copied from the Vector2.
  1786. */
  1787. Vector2.prototype.clone = function () {
  1788. return new Vector2(this.x, this.y);
  1789. };
  1790. // Statics
  1791. /**
  1792. * Returns a new Vector2(0, 0)
  1793. */
  1794. Vector2.Zero = function () {
  1795. return new Vector2(0, 0);
  1796. };
  1797. /**
  1798. * Returns a new Vector2(1, 1)
  1799. */
  1800. Vector2.One = function () {
  1801. return new Vector2(1, 1);
  1802. };
  1803. /**
  1804. * Returns a new Vector2 set from the passed index element of the passed array.
  1805. */
  1806. Vector2.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Vector2(array[offset], array[offset + 1]);
  1809. };
  1810. /**
  1811. * Sets "result" from the passed index element of the passed array.
  1812. */
  1813. Vector2.FromArrayToRef = function (array, offset, result) {
  1814. result.x = array[offset];
  1815. result.y = array[offset + 1];
  1816. };
  1817. /**
  1818. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1819. */
  1820. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1821. var squared = amount * amount;
  1822. var cubed = amount * squared;
  1823. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1824. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1825. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1826. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1827. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1828. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1829. return new Vector2(x, y);
  1830. };
  1831. /**
  1832. * 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".
  1833. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1834. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1835. */
  1836. Vector2.Clamp = function (value, min, max) {
  1837. var x = value.x;
  1838. x = (x > max.x) ? max.x : x;
  1839. x = (x < min.x) ? min.x : x;
  1840. var y = value.y;
  1841. y = (y > max.y) ? max.y : y;
  1842. y = (y < min.y) ? min.y : y;
  1843. return new Vector2(x, y);
  1844. };
  1845. /**
  1846. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1847. */
  1848. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1849. var squared = amount * amount;
  1850. var cubed = amount * squared;
  1851. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1852. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1853. var part3 = (cubed - (2.0 * squared)) + amount;
  1854. var part4 = cubed - squared;
  1855. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1856. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1857. return new Vector2(x, y);
  1858. };
  1859. /**
  1860. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1861. */
  1862. Vector2.Lerp = function (start, end, amount) {
  1863. var x = start.x + ((end.x - start.x) * amount);
  1864. var y = start.y + ((end.y - start.y) * amount);
  1865. return new Vector2(x, y);
  1866. };
  1867. /**
  1868. * Returns the dot product (float) of the vector "left" and the vector "right".
  1869. */
  1870. Vector2.Dot = function (left, right) {
  1871. return left.x * right.x + left.y * right.y;
  1872. };
  1873. /**
  1874. * Returns a new Vector2 equal to the normalized passed vector.
  1875. */
  1876. Vector2.Normalize = function (vector) {
  1877. var newVector = vector.clone();
  1878. newVector.normalize();
  1879. return newVector;
  1880. };
  1881. /**
  1882. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1883. */
  1884. Vector2.Minimize = function (left, right) {
  1885. var x = (left.x < right.x) ? left.x : right.x;
  1886. var y = (left.y < right.y) ? left.y : right.y;
  1887. return new Vector2(x, y);
  1888. };
  1889. /**
  1890. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1891. */
  1892. Vector2.Maximize = function (left, right) {
  1893. var x = (left.x > right.x) ? left.x : right.x;
  1894. var y = (left.y > right.y) ? left.y : right.y;
  1895. return new Vector2(x, y);
  1896. };
  1897. /**
  1898. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1899. */
  1900. Vector2.Transform = function (vector, transformation) {
  1901. var r = Vector2.Zero();
  1902. Vector2.TransformToRef(vector, transformation, r);
  1903. return r;
  1904. };
  1905. /**
  1906. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1907. */
  1908. Vector2.TransformToRef = function (vector, transformation, result) {
  1909. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1910. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1911. result.x = x;
  1912. result.y = y;
  1913. };
  1914. /**
  1915. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1916. */
  1917. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1918. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1919. var sign = a < 0 ? -1 : 1;
  1920. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1921. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1922. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1923. };
  1924. /**
  1925. * Returns the distance (float) between the vectors "value1" and "value2".
  1926. */
  1927. Vector2.Distance = function (value1, value2) {
  1928. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1929. };
  1930. /**
  1931. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1932. */
  1933. Vector2.DistanceSquared = function (value1, value2) {
  1934. var x = value1.x - value2.x;
  1935. var y = value1.y - value2.y;
  1936. return (x * x) + (y * y);
  1937. };
  1938. /**
  1939. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1940. */
  1941. Vector2.Center = function (value1, value2) {
  1942. var center = value1.add(value2);
  1943. center.scaleInPlace(0.5);
  1944. return center;
  1945. };
  1946. /**
  1947. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1948. */
  1949. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1950. var l2 = Vector2.DistanceSquared(segA, segB);
  1951. if (l2 === 0.0) {
  1952. return Vector2.Distance(p, segA);
  1953. }
  1954. var v = segB.subtract(segA);
  1955. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1956. var proj = segA.add(v.multiplyByFloats(t, t));
  1957. return Vector2.Distance(p, proj);
  1958. };
  1959. return Vector2;
  1960. }());
  1961. BABYLON.Vector2 = Vector2;
  1962. var Vector3 = /** @class */ (function () {
  1963. /**
  1964. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1965. * A Vector3 is the main object used in 3D geometry.
  1966. * It can represent etiher the coordinates of a point the space, either a direction.
  1967. */
  1968. function Vector3(x, y, z) {
  1969. this.x = x;
  1970. this.y = y;
  1971. this.z = z;
  1972. }
  1973. /**
  1974. * Returns a string with the Vector3 coordinates.
  1975. */
  1976. Vector3.prototype.toString = function () {
  1977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1978. };
  1979. /**
  1980. * Returns the string "Vector3"
  1981. */
  1982. Vector3.prototype.getClassName = function () {
  1983. return "Vector3";
  1984. };
  1985. /**
  1986. * Returns the Vector hash code.
  1987. */
  1988. Vector3.prototype.getHashCode = function () {
  1989. var hash = this.x || 0;
  1990. hash = (hash * 397) ^ (this.y || 0);
  1991. hash = (hash * 397) ^ (this.z || 0);
  1992. return hash;
  1993. };
  1994. // Operators
  1995. /**
  1996. * Returns a new array with three elements : the coordinates the Vector3.
  1997. */
  1998. Vector3.prototype.asArray = function () {
  1999. var result = [];
  2000. this.toArray(result, 0);
  2001. return result;
  2002. };
  2003. /**
  2004. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2005. * Returns the Vector3.
  2006. */
  2007. Vector3.prototype.toArray = function (array, index) {
  2008. if (index === void 0) { index = 0; }
  2009. array[index] = this.x;
  2010. array[index + 1] = this.y;
  2011. array[index + 2] = this.z;
  2012. return this;
  2013. };
  2014. /**
  2015. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2016. */
  2017. Vector3.prototype.toQuaternion = function () {
  2018. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2019. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2020. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2021. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2022. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2023. var cosy = Math.cos(this.y * 0.5);
  2024. var siny = Math.sin(this.y * 0.5);
  2025. result.x = coszMinusx * siny;
  2026. result.y = -sinzMinusx * siny;
  2027. result.z = sinxPlusz * cosy;
  2028. result.w = cosxPlusz * cosy;
  2029. return result;
  2030. };
  2031. /**
  2032. * Adds the passed vector to the current Vector3.
  2033. * Returns the updated Vector3.
  2034. */
  2035. Vector3.prototype.addInPlace = function (otherVector) {
  2036. this.x += otherVector.x;
  2037. this.y += otherVector.y;
  2038. this.z += otherVector.z;
  2039. return this;
  2040. };
  2041. /**
  2042. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2043. */
  2044. Vector3.prototype.add = function (otherVector) {
  2045. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2046. };
  2047. /**
  2048. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2049. * Returns the current Vector3.
  2050. */
  2051. Vector3.prototype.addToRef = function (otherVector, result) {
  2052. result.x = this.x + otherVector.x;
  2053. result.y = this.y + otherVector.y;
  2054. result.z = this.z + otherVector.z;
  2055. return this;
  2056. };
  2057. /**
  2058. * Subtract the passed vector from the current Vector3.
  2059. * Returns the updated Vector3.
  2060. */
  2061. Vector3.prototype.subtractInPlace = function (otherVector) {
  2062. this.x -= otherVector.x;
  2063. this.y -= otherVector.y;
  2064. this.z -= otherVector.z;
  2065. return this;
  2066. };
  2067. /**
  2068. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2069. */
  2070. Vector3.prototype.subtract = function (otherVector) {
  2071. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2072. };
  2073. /**
  2074. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2075. * Returns the current Vector3.
  2076. */
  2077. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2078. result.x = this.x - otherVector.x;
  2079. result.y = this.y - otherVector.y;
  2080. result.z = this.z - otherVector.z;
  2081. return this;
  2082. };
  2083. /**
  2084. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2085. */
  2086. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2087. return new Vector3(this.x - x, this.y - y, this.z - z);
  2088. };
  2089. /**
  2090. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2091. * Returns the current Vector3.
  2092. */
  2093. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2094. result.x = this.x - x;
  2095. result.y = this.y - y;
  2096. result.z = this.z - z;
  2097. return this;
  2098. };
  2099. /**
  2100. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2101. */
  2102. Vector3.prototype.negate = function () {
  2103. return new Vector3(-this.x, -this.y, -this.z);
  2104. };
  2105. /**
  2106. * Multiplies the Vector3 coordinates by the float "scale".
  2107. * Returns the updated Vector3.
  2108. */
  2109. Vector3.prototype.scaleInPlace = function (scale) {
  2110. this.x *= scale;
  2111. this.y *= scale;
  2112. this.z *= scale;
  2113. return this;
  2114. };
  2115. /**
  2116. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2117. */
  2118. Vector3.prototype.scale = function (scale) {
  2119. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2120. };
  2121. /**
  2122. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2123. * Returns the current Vector3.
  2124. */
  2125. Vector3.prototype.scaleToRef = function (scale, result) {
  2126. result.x = this.x * scale;
  2127. result.y = this.y * scale;
  2128. result.z = this.z * scale;
  2129. return this;
  2130. };
  2131. /**
  2132. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2133. */
  2134. Vector3.prototype.equals = function (otherVector) {
  2135. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2136. };
  2137. /**
  2138. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2139. */
  2140. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2141. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2142. 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);
  2143. };
  2144. /**
  2145. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2146. */
  2147. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2148. return this.x === x && this.y === y && this.z === z;
  2149. };
  2150. /**
  2151. * Muliplies the current Vector3 coordinates by the passed ones.
  2152. * Returns the updated Vector3.
  2153. */
  2154. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2155. this.x *= otherVector.x;
  2156. this.y *= otherVector.y;
  2157. this.z *= otherVector.z;
  2158. return this;
  2159. };
  2160. /**
  2161. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2162. */
  2163. Vector3.prototype.multiply = function (otherVector) {
  2164. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2165. };
  2166. /**
  2167. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2168. * Returns the current Vector3.
  2169. */
  2170. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2171. result.x = this.x * otherVector.x;
  2172. result.y = this.y * otherVector.y;
  2173. result.z = this.z * otherVector.z;
  2174. return this;
  2175. };
  2176. /**
  2177. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2178. */
  2179. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2180. return new Vector3(this.x * x, this.y * y, this.z * z);
  2181. };
  2182. /**
  2183. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2184. */
  2185. Vector3.prototype.divide = function (otherVector) {
  2186. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2187. };
  2188. /**
  2189. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2190. * Returns the current Vector3.
  2191. */
  2192. Vector3.prototype.divideToRef = function (otherVector, result) {
  2193. result.x = this.x / otherVector.x;
  2194. result.y = this.y / otherVector.y;
  2195. result.z = this.z / otherVector.z;
  2196. return this;
  2197. };
  2198. /**
  2199. * Divides the current Vector3 coordinates by the passed ones.
  2200. * Returns the updated Vector3.
  2201. */
  2202. Vector3.prototype.divideInPlace = function (otherVector) {
  2203. return this.divideToRef(otherVector, this);
  2204. };
  2205. /**
  2206. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2207. * Returns the updated Vector3.
  2208. */
  2209. Vector3.prototype.MinimizeInPlace = function (other) {
  2210. if (other.x < this.x)
  2211. this.x = other.x;
  2212. if (other.y < this.y)
  2213. this.y = other.y;
  2214. if (other.z < this.z)
  2215. this.z = other.z;
  2216. return this;
  2217. };
  2218. /**
  2219. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2220. * Returns the updated Vector3.
  2221. */
  2222. Vector3.prototype.MaximizeInPlace = function (other) {
  2223. if (other.x > this.x)
  2224. this.x = other.x;
  2225. if (other.y > this.y)
  2226. this.y = other.y;
  2227. if (other.z > this.z)
  2228. this.z = other.z;
  2229. return this;
  2230. };
  2231. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2232. /**
  2233. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2234. */
  2235. get: function () {
  2236. var absX = Math.abs(this.x);
  2237. var absY = Math.abs(this.y);
  2238. if (absX !== absY) {
  2239. return true;
  2240. }
  2241. var absZ = Math.abs(this.z);
  2242. if (absX !== absZ) {
  2243. return true;
  2244. }
  2245. if (absY !== absZ) {
  2246. return true;
  2247. }
  2248. return false;
  2249. },
  2250. enumerable: true,
  2251. configurable: true
  2252. });
  2253. // Properties
  2254. /**
  2255. * Returns the length of the Vector3 (float).
  2256. */
  2257. Vector3.prototype.length = function () {
  2258. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2259. };
  2260. /**
  2261. * Returns the squared length of the Vector3 (float).
  2262. */
  2263. Vector3.prototype.lengthSquared = function () {
  2264. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2265. };
  2266. /**
  2267. * Normalize the current Vector3.
  2268. * Returns the updated Vector3.
  2269. * /!\ In place operation.
  2270. */
  2271. Vector3.prototype.normalize = function () {
  2272. var len = this.length();
  2273. if (len === 0 || len === 1.0)
  2274. return this;
  2275. var num = 1.0 / len;
  2276. this.x *= num;
  2277. this.y *= num;
  2278. this.z *= num;
  2279. return this;
  2280. };
  2281. /**
  2282. * Normalize the current Vector3 to a new vector.
  2283. * @returns the new Vector3.
  2284. */
  2285. Vector3.prototype.normalizeToNew = function () {
  2286. var normalized = new Vector3(0, 0, 0);
  2287. this.normalizeToRef(normalized);
  2288. return normalized;
  2289. };
  2290. /**
  2291. * Normalize the current Vector3 to the reference.
  2292. * @param the reference to update.
  2293. * @returns the updated Vector3.
  2294. */
  2295. Vector3.prototype.normalizeToRef = function (reference) {
  2296. var len = this.length();
  2297. if (len === 0 || len === 1.0) {
  2298. reference.set(this.x, this.y, this.z);
  2299. return reference;
  2300. }
  2301. var scale = 1.0 / len;
  2302. this.scaleToRef(scale, reference);
  2303. return reference;
  2304. };
  2305. /**
  2306. * Returns a new Vector3 copied from the current Vector3.
  2307. */
  2308. Vector3.prototype.clone = function () {
  2309. return new Vector3(this.x, this.y, this.z);
  2310. };
  2311. /**
  2312. * Copies the passed vector coordinates to the current Vector3 ones.
  2313. * Returns the updated Vector3.
  2314. */
  2315. Vector3.prototype.copyFrom = function (source) {
  2316. this.x = source.x;
  2317. this.y = source.y;
  2318. this.z = source.z;
  2319. return this;
  2320. };
  2321. /**
  2322. * Copies the passed floats to the current Vector3 coordinates.
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2326. this.x = x;
  2327. this.y = y;
  2328. this.z = z;
  2329. return this;
  2330. };
  2331. /**
  2332. * Copies the passed floats to the current Vector3 coordinates.
  2333. * Returns the updated Vector3.
  2334. */
  2335. Vector3.prototype.set = function (x, y, z) {
  2336. return this.copyFromFloats(x, y, z);
  2337. };
  2338. // Statics
  2339. /**
  2340. *
  2341. */
  2342. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2343. var d0 = Vector3.Dot(vector0, axis) - size;
  2344. var d1 = Vector3.Dot(vector1, axis) - size;
  2345. var s = d0 / (d0 - d1);
  2346. return s;
  2347. };
  2348. /**
  2349. * Returns a new Vector3 set from the index "offset" of the passed array.
  2350. */
  2351. Vector3.FromArray = function (array, offset) {
  2352. if (!offset) {
  2353. offset = 0;
  2354. }
  2355. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2356. };
  2357. /**
  2358. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2359. * This function is deprecated. Use FromArray instead.
  2360. */
  2361. Vector3.FromFloatArray = function (array, offset) {
  2362. return Vector3.FromArray(array, offset);
  2363. };
  2364. /**
  2365. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2366. */
  2367. Vector3.FromArrayToRef = function (array, offset, result) {
  2368. result.x = array[offset];
  2369. result.y = array[offset + 1];
  2370. result.z = array[offset + 2];
  2371. };
  2372. /**
  2373. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2374. * This function is deprecated. Use FromArrayToRef instead.
  2375. */
  2376. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2377. return Vector3.FromArrayToRef(array, offset, result);
  2378. };
  2379. /**
  2380. * Sets the passed vector "result" with the passed floats.
  2381. */
  2382. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2383. result.x = x;
  2384. result.y = y;
  2385. result.z = z;
  2386. };
  2387. /**
  2388. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2389. */
  2390. Vector3.Zero = function () {
  2391. return new Vector3(0.0, 0.0, 0.0);
  2392. };
  2393. /**
  2394. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2395. */
  2396. Vector3.One = function () {
  2397. return new Vector3(1.0, 1.0, 1.0);
  2398. };
  2399. /**
  2400. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2401. */
  2402. Vector3.Up = function () {
  2403. return new Vector3(0.0, 1.0, 0.0);
  2404. };
  2405. /**
  2406. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2407. */
  2408. Vector3.Forward = function () {
  2409. return new Vector3(0.0, 0.0, 1.0);
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2413. */
  2414. Vector3.Right = function () {
  2415. return new Vector3(1.0, 0.0, 0.0);
  2416. };
  2417. /**
  2418. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2419. */
  2420. Vector3.Left = function () {
  2421. return new Vector3(-1.0, 0.0, 0.0);
  2422. };
  2423. /**
  2424. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2425. * This method computes tranformed coordinates only, not transformed direction vectors.
  2426. */
  2427. Vector3.TransformCoordinates = function (vector, transformation) {
  2428. var result = Vector3.Zero();
  2429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2430. return result;
  2431. };
  2432. /**
  2433. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2434. * This method computes tranformed coordinates only, not transformed direction vectors.
  2435. */
  2436. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2437. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2438. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2439. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2440. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2441. result.x = x / w;
  2442. result.y = y / w;
  2443. result.z = z / w;
  2444. };
  2445. /**
  2446. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2447. * This method computes tranformed coordinates only, not transformed direction vectors.
  2448. */
  2449. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2450. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2451. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2452. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2453. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2454. result.x = rx / rw;
  2455. result.y = ry / rw;
  2456. result.z = rz / rw;
  2457. };
  2458. /**
  2459. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2460. * This methods computes transformed normalized direction vectors only.
  2461. */
  2462. Vector3.TransformNormal = function (vector, transformation) {
  2463. var result = Vector3.Zero();
  2464. Vector3.TransformNormalToRef(vector, transformation, result);
  2465. return result;
  2466. };
  2467. /**
  2468. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2469. * This methods computes transformed normalized direction vectors only.
  2470. */
  2471. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2472. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2473. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2474. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2475. result.x = x;
  2476. result.y = y;
  2477. result.z = z;
  2478. };
  2479. /**
  2480. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2481. * This methods computes transformed normalized direction vectors only.
  2482. */
  2483. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2484. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2485. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2486. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2487. };
  2488. /**
  2489. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2490. */
  2491. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2492. var squared = amount * amount;
  2493. var cubed = amount * squared;
  2494. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2495. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2496. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2497. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2498. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2499. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2500. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2501. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2502. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2503. return new Vector3(x, y, z);
  2504. };
  2505. /**
  2506. * 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".
  2507. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2508. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2509. */
  2510. Vector3.Clamp = function (value, min, max) {
  2511. var x = value.x;
  2512. x = (x > max.x) ? max.x : x;
  2513. x = (x < min.x) ? min.x : x;
  2514. var y = value.y;
  2515. y = (y > max.y) ? max.y : y;
  2516. y = (y < min.y) ? min.y : y;
  2517. var z = value.z;
  2518. z = (z > max.z) ? max.z : z;
  2519. z = (z < min.z) ? min.z : z;
  2520. return new Vector3(x, y, z);
  2521. };
  2522. /**
  2523. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2524. */
  2525. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2526. var squared = amount * amount;
  2527. var cubed = amount * squared;
  2528. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2529. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2530. var part3 = (cubed - (2.0 * squared)) + amount;
  2531. var part4 = cubed - squared;
  2532. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2533. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2534. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2535. return new Vector3(x, y, z);
  2536. };
  2537. /**
  2538. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2539. */
  2540. Vector3.Lerp = function (start, end, amount) {
  2541. var result = new Vector3(0, 0, 0);
  2542. Vector3.LerpToRef(start, end, amount, result);
  2543. return result;
  2544. };
  2545. /**
  2546. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2547. */
  2548. Vector3.LerpToRef = function (start, end, amount, result) {
  2549. result.x = start.x + ((end.x - start.x) * amount);
  2550. result.y = start.y + ((end.y - start.y) * amount);
  2551. result.z = start.z + ((end.z - start.z) * amount);
  2552. };
  2553. /**
  2554. * Returns the dot product (float) between the vectors "left" and "right".
  2555. */
  2556. Vector3.Dot = function (left, right) {
  2557. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2558. };
  2559. /**
  2560. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2561. * The cross product is then orthogonal to both "left" and "right".
  2562. */
  2563. Vector3.Cross = function (left, right) {
  2564. var result = Vector3.Zero();
  2565. Vector3.CrossToRef(left, right, result);
  2566. return result;
  2567. };
  2568. /**
  2569. * Sets the passed vector "result" with the cross product of "left" and "right".
  2570. * The cross product is then orthogonal to both "left" and "right".
  2571. */
  2572. Vector3.CrossToRef = function (left, right, result) {
  2573. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2574. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2575. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2576. result.copyFrom(MathTmp.Vector3[0]);
  2577. };
  2578. /**
  2579. * Returns a new Vector3 as the normalization of the passed vector.
  2580. */
  2581. Vector3.Normalize = function (vector) {
  2582. var result = Vector3.Zero();
  2583. Vector3.NormalizeToRef(vector, result);
  2584. return result;
  2585. };
  2586. /**
  2587. * Sets the passed vector "result" with the normalization of the passed first vector.
  2588. */
  2589. Vector3.NormalizeToRef = function (vector, result) {
  2590. result.copyFrom(vector);
  2591. result.normalize();
  2592. };
  2593. Vector3.Project = function (vector, world, transform, viewport) {
  2594. var cw = viewport.width;
  2595. var ch = viewport.height;
  2596. var cx = viewport.x;
  2597. var cy = viewport.y;
  2598. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2599. 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);
  2600. var matrix = MathTmp.Matrix[0];
  2601. world.multiplyToRef(transform, matrix);
  2602. matrix.multiplyToRef(viewportMatrix, matrix);
  2603. return Vector3.TransformCoordinates(vector, matrix);
  2604. };
  2605. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2606. var matrix = MathTmp.Matrix[0];
  2607. world.multiplyToRef(transform, matrix);
  2608. matrix.invert();
  2609. source.x = source.x / viewportWidth * 2 - 1;
  2610. source.y = -(source.y / viewportHeight * 2 - 1);
  2611. var vector = Vector3.TransformCoordinates(source, matrix);
  2612. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2613. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2614. vector = vector.scale(1.0 / num);
  2615. }
  2616. return vector;
  2617. };
  2618. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2619. var result = Vector3.Zero();
  2620. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2621. return result;
  2622. };
  2623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2625. };
  2626. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2627. var matrix = MathTmp.Matrix[0];
  2628. world.multiplyToRef(view, matrix);
  2629. matrix.multiplyToRef(projection, matrix);
  2630. matrix.invert();
  2631. var screenSource = MathTmp.Vector3[0];
  2632. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2633. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2634. screenSource.z = 2 * sourceZ - 1.0;
  2635. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2636. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2637. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2638. result.scaleInPlace(1.0 / num);
  2639. }
  2640. };
  2641. Vector3.Minimize = function (left, right) {
  2642. var min = left.clone();
  2643. min.MinimizeInPlace(right);
  2644. return min;
  2645. };
  2646. Vector3.Maximize = function (left, right) {
  2647. var max = left.clone();
  2648. max.MaximizeInPlace(right);
  2649. return max;
  2650. };
  2651. /**
  2652. * Returns the distance (float) between the vectors "value1" and "value2".
  2653. */
  2654. Vector3.Distance = function (value1, value2) {
  2655. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2656. };
  2657. /**
  2658. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2659. */
  2660. Vector3.DistanceSquared = function (value1, value2) {
  2661. var x = value1.x - value2.x;
  2662. var y = value1.y - value2.y;
  2663. var z = value1.z - value2.z;
  2664. return (x * x) + (y * y) + (z * z);
  2665. };
  2666. /**
  2667. * Returns a new Vector3 located at the center between "value1" and "value2".
  2668. */
  2669. Vector3.Center = function (value1, value2) {
  2670. var center = value1.add(value2);
  2671. center.scaleInPlace(0.5);
  2672. return center;
  2673. };
  2674. /**
  2675. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2676. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2677. * to something in order to rotate it from its local system to the given target system.
  2678. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2679. * Returns a new Vector3.
  2680. */
  2681. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2682. var rotation = Vector3.Zero();
  2683. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2684. return rotation;
  2685. };
  2686. /**
  2687. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2688. */
  2689. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2690. var quat = MathTmp.Quaternion[0];
  2691. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2692. quat.toEulerAnglesToRef(ref);
  2693. };
  2694. return Vector3;
  2695. }());
  2696. BABYLON.Vector3 = Vector3;
  2697. //Vector4 class created for EulerAngle class conversion to Quaternion
  2698. var Vector4 = /** @class */ (function () {
  2699. /**
  2700. * Creates a Vector4 object from the passed floats.
  2701. */
  2702. function Vector4(x, y, z, w) {
  2703. this.x = x;
  2704. this.y = y;
  2705. this.z = z;
  2706. this.w = w;
  2707. }
  2708. /**
  2709. * Returns the string with the Vector4 coordinates.
  2710. */
  2711. Vector4.prototype.toString = function () {
  2712. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2713. };
  2714. /**
  2715. * Returns the string "Vector4".
  2716. */
  2717. Vector4.prototype.getClassName = function () {
  2718. return "Vector4";
  2719. };
  2720. /**
  2721. * Returns the Vector4 hash code.
  2722. */
  2723. Vector4.prototype.getHashCode = function () {
  2724. var hash = this.x || 0;
  2725. hash = (hash * 397) ^ (this.y || 0);
  2726. hash = (hash * 397) ^ (this.z || 0);
  2727. hash = (hash * 397) ^ (this.w || 0);
  2728. return hash;
  2729. };
  2730. // Operators
  2731. /**
  2732. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2733. */
  2734. Vector4.prototype.asArray = function () {
  2735. var result = new Array();
  2736. this.toArray(result, 0);
  2737. return result;
  2738. };
  2739. /**
  2740. * Populates the passed array from the passed index with the Vector4 coordinates.
  2741. * Returns the Vector4.
  2742. */
  2743. Vector4.prototype.toArray = function (array, index) {
  2744. if (index === undefined) {
  2745. index = 0;
  2746. }
  2747. array[index] = this.x;
  2748. array[index + 1] = this.y;
  2749. array[index + 2] = this.z;
  2750. array[index + 3] = this.w;
  2751. return this;
  2752. };
  2753. /**
  2754. * Adds the passed vector to the current Vector4.
  2755. * Returns the updated Vector4.
  2756. */
  2757. Vector4.prototype.addInPlace = function (otherVector) {
  2758. this.x += otherVector.x;
  2759. this.y += otherVector.y;
  2760. this.z += otherVector.z;
  2761. this.w += otherVector.w;
  2762. return this;
  2763. };
  2764. /**
  2765. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2766. */
  2767. Vector4.prototype.add = function (otherVector) {
  2768. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2769. };
  2770. /**
  2771. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2772. * Returns the current Vector4.
  2773. */
  2774. Vector4.prototype.addToRef = function (otherVector, result) {
  2775. result.x = this.x + otherVector.x;
  2776. result.y = this.y + otherVector.y;
  2777. result.z = this.z + otherVector.z;
  2778. result.w = this.w + otherVector.w;
  2779. return this;
  2780. };
  2781. /**
  2782. * Subtract in place the passed vector from the current Vector4.
  2783. * Returns the updated Vector4.
  2784. */
  2785. Vector4.prototype.subtractInPlace = function (otherVector) {
  2786. this.x -= otherVector.x;
  2787. this.y -= otherVector.y;
  2788. this.z -= otherVector.z;
  2789. this.w -= otherVector.w;
  2790. return this;
  2791. };
  2792. /**
  2793. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2794. */
  2795. Vector4.prototype.subtract = function (otherVector) {
  2796. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2797. };
  2798. /**
  2799. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2800. * Returns the current Vector4.
  2801. */
  2802. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2803. result.x = this.x - otherVector.x;
  2804. result.y = this.y - otherVector.y;
  2805. result.z = this.z - otherVector.z;
  2806. result.w = this.w - otherVector.w;
  2807. return this;
  2808. };
  2809. /**
  2810. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2811. */
  2812. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2813. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2814. };
  2815. /**
  2816. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2817. * Returns the current Vector4.
  2818. */
  2819. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2820. result.x = this.x - x;
  2821. result.y = this.y - y;
  2822. result.z = this.z - z;
  2823. result.w = this.w - w;
  2824. return this;
  2825. };
  2826. /**
  2827. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2828. */
  2829. Vector4.prototype.negate = function () {
  2830. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2831. };
  2832. /**
  2833. * Multiplies the current Vector4 coordinates by scale (float).
  2834. * Returns the updated Vector4.
  2835. */
  2836. Vector4.prototype.scaleInPlace = function (scale) {
  2837. this.x *= scale;
  2838. this.y *= scale;
  2839. this.z *= scale;
  2840. this.w *= scale;
  2841. return this;
  2842. };
  2843. /**
  2844. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2845. */
  2846. Vector4.prototype.scale = function (scale) {
  2847. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2848. };
  2849. /**
  2850. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2851. * Returns the current Vector4.
  2852. */
  2853. Vector4.prototype.scaleToRef = function (scale, result) {
  2854. result.x = this.x * scale;
  2855. result.y = this.y * scale;
  2856. result.z = this.z * scale;
  2857. result.w = this.w * scale;
  2858. return this;
  2859. };
  2860. /**
  2861. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2862. */
  2863. Vector4.prototype.equals = function (otherVector) {
  2864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2865. };
  2866. /**
  2867. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2868. */
  2869. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2870. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2871. return otherVector
  2872. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2873. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2874. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2875. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2876. };
  2877. /**
  2878. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2879. */
  2880. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2881. return this.x === x && this.y === y && this.z === z && this.w === w;
  2882. };
  2883. /**
  2884. * Multiplies in place the current Vector4 by the passed one.
  2885. * Returns the updated Vector4.
  2886. */
  2887. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2888. this.x *= otherVector.x;
  2889. this.y *= otherVector.y;
  2890. this.z *= otherVector.z;
  2891. this.w *= otherVector.w;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2896. */
  2897. Vector4.prototype.multiply = function (otherVector) {
  2898. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2899. };
  2900. /**
  2901. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2902. * Returns the current Vector4.
  2903. */
  2904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2905. result.x = this.x * otherVector.x;
  2906. result.y = this.y * otherVector.y;
  2907. result.z = this.z * otherVector.z;
  2908. result.w = this.w * otherVector.w;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2913. */
  2914. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2915. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2916. };
  2917. /**
  2918. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2919. */
  2920. Vector4.prototype.divide = function (otherVector) {
  2921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2922. };
  2923. /**
  2924. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2925. * Returns the current Vector4.
  2926. */
  2927. Vector4.prototype.divideToRef = function (otherVector, result) {
  2928. result.x = this.x / otherVector.x;
  2929. result.y = this.y / otherVector.y;
  2930. result.z = this.z / otherVector.z;
  2931. result.w = this.w / otherVector.w;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * Returns the updated Vector3.
  2937. */
  2938. Vector4.prototype.divideInPlace = function (otherVector) {
  2939. return this.divideToRef(otherVector, this);
  2940. };
  2941. /**
  2942. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2943. */
  2944. Vector4.prototype.MinimizeInPlace = function (other) {
  2945. if (other.x < this.x)
  2946. this.x = other.x;
  2947. if (other.y < this.y)
  2948. this.y = other.y;
  2949. if (other.z < this.z)
  2950. this.z = other.z;
  2951. if (other.w < this.w)
  2952. this.w = other.w;
  2953. return this;
  2954. };
  2955. /**
  2956. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2957. */
  2958. Vector4.prototype.MaximizeInPlace = function (other) {
  2959. if (other.x > this.x)
  2960. this.x = other.x;
  2961. if (other.y > this.y)
  2962. this.y = other.y;
  2963. if (other.z > this.z)
  2964. this.z = other.z;
  2965. if (other.w > this.w)
  2966. this.w = other.w;
  2967. return this;
  2968. };
  2969. // Properties
  2970. /**
  2971. * Returns the Vector4 length (float).
  2972. */
  2973. Vector4.prototype.length = function () {
  2974. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2975. };
  2976. /**
  2977. * Returns the Vector4 squared length (float).
  2978. */
  2979. Vector4.prototype.lengthSquared = function () {
  2980. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2981. };
  2982. // Methods
  2983. /**
  2984. * Normalizes in place the Vector4.
  2985. * Returns the updated Vector4.
  2986. */
  2987. Vector4.prototype.normalize = function () {
  2988. var len = this.length();
  2989. if (len === 0)
  2990. return this;
  2991. var num = 1.0 / len;
  2992. this.x *= num;
  2993. this.y *= num;
  2994. this.z *= num;
  2995. this.w *= num;
  2996. return this;
  2997. };
  2998. /**
  2999. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3000. */
  3001. Vector4.prototype.toVector3 = function () {
  3002. return new Vector3(this.x, this.y, this.z);
  3003. };
  3004. /**
  3005. * Returns a new Vector4 copied from the current one.
  3006. */
  3007. Vector4.prototype.clone = function () {
  3008. return new Vector4(this.x, this.y, this.z, this.w);
  3009. };
  3010. /**
  3011. * Updates the current Vector4 with the passed one coordinates.
  3012. * Returns the updated Vector4.
  3013. */
  3014. Vector4.prototype.copyFrom = function (source) {
  3015. this.x = source.x;
  3016. this.y = source.y;
  3017. this.z = source.z;
  3018. this.w = source.w;
  3019. return this;
  3020. };
  3021. /**
  3022. * Updates the current Vector4 coordinates with the passed floats.
  3023. * Returns the updated Vector4.
  3024. */
  3025. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3026. this.x = x;
  3027. this.y = y;
  3028. this.z = z;
  3029. this.w = w;
  3030. return this;
  3031. };
  3032. /**
  3033. * Updates the current Vector4 coordinates with the passed floats.
  3034. * Returns the updated Vector4.
  3035. */
  3036. Vector4.prototype.set = function (x, y, z, w) {
  3037. return this.copyFromFloats(x, y, z, w);
  3038. };
  3039. // Statics
  3040. /**
  3041. * Returns a new Vector4 set from the starting index of the passed array.
  3042. */
  3043. Vector4.FromArray = function (array, offset) {
  3044. if (!offset) {
  3045. offset = 0;
  3046. }
  3047. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3048. };
  3049. /**
  3050. * Updates the passed vector "result" from the starting index of the passed array.
  3051. */
  3052. Vector4.FromArrayToRef = function (array, offset, result) {
  3053. result.x = array[offset];
  3054. result.y = array[offset + 1];
  3055. result.z = array[offset + 2];
  3056. result.w = array[offset + 3];
  3057. };
  3058. /**
  3059. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3060. */
  3061. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3062. Vector4.FromArrayToRef(array, offset, result);
  3063. };
  3064. /**
  3065. * Updates the passed vector "result" coordinates from the passed floats.
  3066. */
  3067. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3068. result.x = x;
  3069. result.y = y;
  3070. result.z = z;
  3071. result.w = w;
  3072. };
  3073. /**
  3074. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3075. */
  3076. Vector4.Zero = function () {
  3077. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3078. };
  3079. /**
  3080. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3081. */
  3082. Vector4.One = function () {
  3083. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3084. };
  3085. /**
  3086. * Returns a new normalized Vector4 from the passed one.
  3087. */
  3088. Vector4.Normalize = function (vector) {
  3089. var result = Vector4.Zero();
  3090. Vector4.NormalizeToRef(vector, result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Updates the passed vector "result" from the normalization of the passed one.
  3095. */
  3096. Vector4.NormalizeToRef = function (vector, result) {
  3097. result.copyFrom(vector);
  3098. result.normalize();
  3099. };
  3100. Vector4.Minimize = function (left, right) {
  3101. var min = left.clone();
  3102. min.MinimizeInPlace(right);
  3103. return min;
  3104. };
  3105. Vector4.Maximize = function (left, right) {
  3106. var max = left.clone();
  3107. max.MaximizeInPlace(right);
  3108. return max;
  3109. };
  3110. /**
  3111. * Returns the distance (float) between the vectors "value1" and "value2".
  3112. */
  3113. Vector4.Distance = function (value1, value2) {
  3114. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3115. };
  3116. /**
  3117. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3118. */
  3119. Vector4.DistanceSquared = function (value1, value2) {
  3120. var x = value1.x - value2.x;
  3121. var y = value1.y - value2.y;
  3122. var z = value1.z - value2.z;
  3123. var w = value1.w - value2.w;
  3124. return (x * x) + (y * y) + (z * z) + (w * w);
  3125. };
  3126. /**
  3127. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3128. */
  3129. Vector4.Center = function (value1, value2) {
  3130. var center = value1.add(value2);
  3131. center.scaleInPlace(0.5);
  3132. return center;
  3133. };
  3134. /**
  3135. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3136. * This methods computes transformed normalized direction vectors only.
  3137. */
  3138. Vector4.TransformNormal = function (vector, transformation) {
  3139. var result = Vector4.Zero();
  3140. Vector4.TransformNormalToRef(vector, transformation, result);
  3141. return result;
  3142. };
  3143. /**
  3144. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3145. * This methods computes transformed normalized direction vectors only.
  3146. */
  3147. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3148. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3149. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3150. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3151. result.x = x;
  3152. result.y = y;
  3153. result.z = z;
  3154. result.w = vector.w;
  3155. };
  3156. /**
  3157. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3158. * This methods computes transformed normalized direction vectors only.
  3159. */
  3160. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3161. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3162. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3163. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3164. result.w = w;
  3165. };
  3166. return Vector4;
  3167. }());
  3168. BABYLON.Vector4 = Vector4;
  3169. var Size = /** @class */ (function () {
  3170. /**
  3171. * Creates a Size object from the passed width and height (floats).
  3172. */
  3173. function Size(width, height) {
  3174. this.width = width;
  3175. this.height = height;
  3176. }
  3177. // Returns a string with the Size width and height.
  3178. Size.prototype.toString = function () {
  3179. return "{W: " + this.width + ", H: " + this.height + "}";
  3180. };
  3181. /**
  3182. * Returns the string "Size"
  3183. */
  3184. Size.prototype.getClassName = function () {
  3185. return "Size";
  3186. };
  3187. /**
  3188. * Returns the Size hash code.
  3189. */
  3190. Size.prototype.getHashCode = function () {
  3191. var hash = this.width || 0;
  3192. hash = (hash * 397) ^ (this.height || 0);
  3193. return hash;
  3194. };
  3195. /**
  3196. * Updates the current size from the passed one.
  3197. * Returns the updated Size.
  3198. */
  3199. Size.prototype.copyFrom = function (src) {
  3200. this.width = src.width;
  3201. this.height = src.height;
  3202. };
  3203. /**
  3204. * Updates in place the current Size from the passed floats.
  3205. * Returns the updated Size.
  3206. */
  3207. Size.prototype.copyFromFloats = function (width, height) {
  3208. this.width = width;
  3209. this.height = height;
  3210. return this;
  3211. };
  3212. /**
  3213. * Updates in place the current Size from the passed floats.
  3214. * Returns the updated Size.
  3215. */
  3216. Size.prototype.set = function (width, height) {
  3217. return this.copyFromFloats(width, height);
  3218. };
  3219. /**
  3220. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3221. */
  3222. Size.prototype.multiplyByFloats = function (w, h) {
  3223. return new Size(this.width * w, this.height * h);
  3224. };
  3225. /**
  3226. * Returns a new Size copied from the passed one.
  3227. */
  3228. Size.prototype.clone = function () {
  3229. return new Size(this.width, this.height);
  3230. };
  3231. /**
  3232. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3233. */
  3234. Size.prototype.equals = function (other) {
  3235. if (!other) {
  3236. return false;
  3237. }
  3238. return (this.width === other.width) && (this.height === other.height);
  3239. };
  3240. Object.defineProperty(Size.prototype, "surface", {
  3241. /**
  3242. * Returns the surface of the Size : width * height (float).
  3243. */
  3244. get: function () {
  3245. return this.width * this.height;
  3246. },
  3247. enumerable: true,
  3248. configurable: true
  3249. });
  3250. /**
  3251. * Returns a new Size set to (0.0, 0.0)
  3252. */
  3253. Size.Zero = function () {
  3254. return new Size(0.0, 0.0);
  3255. };
  3256. /**
  3257. * Returns a new Size set as the addition result of the current Size and the passed one.
  3258. */
  3259. Size.prototype.add = function (otherSize) {
  3260. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3261. return r;
  3262. };
  3263. /**
  3264. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3265. */
  3266. Size.prototype.subtract = function (otherSize) {
  3267. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3268. return r;
  3269. };
  3270. /**
  3271. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3272. */
  3273. Size.Lerp = function (start, end, amount) {
  3274. var w = start.width + ((end.width - start.width) * amount);
  3275. var h = start.height + ((end.height - start.height) * amount);
  3276. return new Size(w, h);
  3277. };
  3278. return Size;
  3279. }());
  3280. BABYLON.Size = Size;
  3281. var Quaternion = /** @class */ (function () {
  3282. /**
  3283. * Creates a new Quaternion from the passed floats.
  3284. */
  3285. function Quaternion(x, y, z, w) {
  3286. if (x === void 0) { x = 0.0; }
  3287. if (y === void 0) { y = 0.0; }
  3288. if (z === void 0) { z = 0.0; }
  3289. if (w === void 0) { w = 1.0; }
  3290. this.x = x;
  3291. this.y = y;
  3292. this.z = z;
  3293. this.w = w;
  3294. }
  3295. /**
  3296. * Returns a string with the Quaternion coordinates.
  3297. */
  3298. Quaternion.prototype.toString = function () {
  3299. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3300. };
  3301. /**
  3302. * Returns the string "Quaternion".
  3303. */
  3304. Quaternion.prototype.getClassName = function () {
  3305. return "Quaternion";
  3306. };
  3307. /**
  3308. * Returns the Quaternion hash code.
  3309. */
  3310. Quaternion.prototype.getHashCode = function () {
  3311. var hash = this.x || 0;
  3312. hash = (hash * 397) ^ (this.y || 0);
  3313. hash = (hash * 397) ^ (this.z || 0);
  3314. hash = (hash * 397) ^ (this.w || 0);
  3315. return hash;
  3316. };
  3317. /**
  3318. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3319. */
  3320. Quaternion.prototype.asArray = function () {
  3321. return [this.x, this.y, this.z, this.w];
  3322. };
  3323. /**
  3324. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3325. */
  3326. Quaternion.prototype.equals = function (otherQuaternion) {
  3327. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3328. };
  3329. /**
  3330. * Returns a new Quaternion copied from the current one.
  3331. */
  3332. Quaternion.prototype.clone = function () {
  3333. return new Quaternion(this.x, this.y, this.z, this.w);
  3334. };
  3335. /**
  3336. * Updates the current Quaternion from the passed one coordinates.
  3337. * Returns the updated Quaterion.
  3338. */
  3339. Quaternion.prototype.copyFrom = function (other) {
  3340. this.x = other.x;
  3341. this.y = other.y;
  3342. this.z = other.z;
  3343. this.w = other.w;
  3344. return this;
  3345. };
  3346. /**
  3347. * Updates the current Quaternion from the passed float coordinates.
  3348. * Returns the updated Quaterion.
  3349. */
  3350. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3351. this.x = x;
  3352. this.y = y;
  3353. this.z = z;
  3354. this.w = w;
  3355. return this;
  3356. };
  3357. /**
  3358. * Updates the current Quaternion from the passed float coordinates.
  3359. * Returns the updated Quaterion.
  3360. */
  3361. Quaternion.prototype.set = function (x, y, z, w) {
  3362. return this.copyFromFloats(x, y, z, w);
  3363. };
  3364. /**
  3365. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3366. */
  3367. Quaternion.prototype.add = function (other) {
  3368. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3369. };
  3370. /**
  3371. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3372. */
  3373. Quaternion.prototype.subtract = function (other) {
  3374. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3375. };
  3376. /**
  3377. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3378. */
  3379. Quaternion.prototype.scale = function (value) {
  3380. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3381. };
  3382. /**
  3383. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3384. */
  3385. Quaternion.prototype.multiply = function (q1) {
  3386. var result = new Quaternion(0, 0, 0, 1.0);
  3387. this.multiplyToRef(q1, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3392. * Returns the current Quaternion.
  3393. */
  3394. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3395. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3396. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3397. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3398. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3399. result.copyFromFloats(x, y, z, w);
  3400. return this;
  3401. };
  3402. /**
  3403. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3404. * Returns the updated Quaternion.
  3405. */
  3406. Quaternion.prototype.multiplyInPlace = function (q1) {
  3407. this.multiplyToRef(q1, this);
  3408. return this;
  3409. };
  3410. /**
  3411. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3412. * Returns the current Quaternion.
  3413. */
  3414. Quaternion.prototype.conjugateToRef = function (ref) {
  3415. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3416. return this;
  3417. };
  3418. /**
  3419. * Conjugates in place the current Quaternion.
  3420. * Returns the updated Quaternion.
  3421. */
  3422. Quaternion.prototype.conjugateInPlace = function () {
  3423. this.x *= -1;
  3424. this.y *= -1;
  3425. this.z *= -1;
  3426. return this;
  3427. };
  3428. /**
  3429. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3430. */
  3431. Quaternion.prototype.conjugate = function () {
  3432. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3433. return result;
  3434. };
  3435. /**
  3436. * Returns the Quaternion length (float).
  3437. */
  3438. Quaternion.prototype.length = function () {
  3439. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3440. };
  3441. /**
  3442. * Normalize in place the current Quaternion.
  3443. * Returns the updated Quaternion.
  3444. */
  3445. Quaternion.prototype.normalize = function () {
  3446. var length = 1.0 / this.length();
  3447. this.x *= length;
  3448. this.y *= length;
  3449. this.z *= length;
  3450. this.w *= length;
  3451. return this;
  3452. };
  3453. /**
  3454. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3455. */
  3456. Quaternion.prototype.toEulerAngles = function (order) {
  3457. if (order === void 0) { order = "YZX"; }
  3458. var result = Vector3.Zero();
  3459. this.toEulerAnglesToRef(result, order);
  3460. return result;
  3461. };
  3462. /**
  3463. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3464. * Returns the current Quaternion.
  3465. */
  3466. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3467. if (order === void 0) { order = "YZX"; }
  3468. var qz = this.z;
  3469. var qx = this.x;
  3470. var qy = this.y;
  3471. var qw = this.w;
  3472. var sqw = qw * qw;
  3473. var sqz = qz * qz;
  3474. var sqx = qx * qx;
  3475. var sqy = qy * qy;
  3476. var zAxisY = qy * qz - qx * qw;
  3477. var limit = .4999999;
  3478. if (zAxisY < -limit) {
  3479. result.y = 2 * Math.atan2(qy, qw);
  3480. result.x = Math.PI / 2;
  3481. result.z = 0;
  3482. }
  3483. else if (zAxisY > limit) {
  3484. result.y = 2 * Math.atan2(qy, qw);
  3485. result.x = -Math.PI / 2;
  3486. result.z = 0;
  3487. }
  3488. else {
  3489. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3490. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3491. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3492. }
  3493. return this;
  3494. };
  3495. /**
  3496. * Updates the passed rotation matrix with the current Quaternion values.
  3497. * Returns the current Quaternion.
  3498. */
  3499. Quaternion.prototype.toRotationMatrix = function (result) {
  3500. var xx = this.x * this.x;
  3501. var yy = this.y * this.y;
  3502. var zz = this.z * this.z;
  3503. var xy = this.x * this.y;
  3504. var zw = this.z * this.w;
  3505. var zx = this.z * this.x;
  3506. var yw = this.y * this.w;
  3507. var yz = this.y * this.z;
  3508. var xw = this.x * this.w;
  3509. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3510. result.m[1] = 2.0 * (xy + zw);
  3511. result.m[2] = 2.0 * (zx - yw);
  3512. result.m[3] = 0;
  3513. result.m[4] = 2.0 * (xy - zw);
  3514. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3515. result.m[6] = 2.0 * (yz + xw);
  3516. result.m[7] = 0;
  3517. result.m[8] = 2.0 * (zx + yw);
  3518. result.m[9] = 2.0 * (yz - xw);
  3519. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3520. result.m[11] = 0;
  3521. result.m[12] = 0;
  3522. result.m[13] = 0;
  3523. result.m[14] = 0;
  3524. result.m[15] = 1.0;
  3525. result._markAsUpdated();
  3526. return this;
  3527. };
  3528. /**
  3529. * Updates the current Quaternion from the passed rotation matrix values.
  3530. * Returns the updated Quaternion.
  3531. */
  3532. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3533. Quaternion.FromRotationMatrixToRef(matrix, this);
  3534. return this;
  3535. };
  3536. // Statics
  3537. /**
  3538. * Returns a new Quaternion set from the passed rotation matrix values.
  3539. */
  3540. Quaternion.FromRotationMatrix = function (matrix) {
  3541. var result = new Quaternion();
  3542. Quaternion.FromRotationMatrixToRef(matrix, result);
  3543. return result;
  3544. };
  3545. /**
  3546. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3547. */
  3548. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3549. var data = matrix.m;
  3550. var m11 = data[0], m12 = data[4], m13 = data[8];
  3551. var m21 = data[1], m22 = data[5], m23 = data[9];
  3552. var m31 = data[2], m32 = data[6], m33 = data[10];
  3553. var trace = m11 + m22 + m33;
  3554. var s;
  3555. if (trace > 0) {
  3556. s = 0.5 / Math.sqrt(trace + 1.0);
  3557. result.w = 0.25 / s;
  3558. result.x = (m32 - m23) * s;
  3559. result.y = (m13 - m31) * s;
  3560. result.z = (m21 - m12) * s;
  3561. }
  3562. else if (m11 > m22 && m11 > m33) {
  3563. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3564. result.w = (m32 - m23) / s;
  3565. result.x = 0.25 * s;
  3566. result.y = (m12 + m21) / s;
  3567. result.z = (m13 + m31) / s;
  3568. }
  3569. else if (m22 > m33) {
  3570. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3571. result.w = (m13 - m31) / s;
  3572. result.x = (m12 + m21) / s;
  3573. result.y = 0.25 * s;
  3574. result.z = (m23 + m32) / s;
  3575. }
  3576. else {
  3577. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3578. result.w = (m21 - m12) / s;
  3579. result.x = (m13 + m31) / s;
  3580. result.y = (m23 + m32) / s;
  3581. result.z = 0.25 * s;
  3582. }
  3583. };
  3584. /**
  3585. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3586. */
  3587. Quaternion.Zero = function () {
  3588. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3589. };
  3590. /**
  3591. * Returns a new Quaternion as the inverted current Quaternion.
  3592. */
  3593. Quaternion.Inverse = function (q) {
  3594. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3595. };
  3596. /**
  3597. * Returns the identity Quaternion.
  3598. */
  3599. Quaternion.Identity = function () {
  3600. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3601. };
  3602. Quaternion.IsIdentity = function (quaternion) {
  3603. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3604. };
  3605. /**
  3606. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3607. */
  3608. Quaternion.RotationAxis = function (axis, angle) {
  3609. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3610. };
  3611. /**
  3612. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3613. */
  3614. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3615. var sin = Math.sin(angle / 2);
  3616. axis.normalize();
  3617. result.w = Math.cos(angle / 2);
  3618. result.x = axis.x * sin;
  3619. result.y = axis.y * sin;
  3620. result.z = axis.z * sin;
  3621. return result;
  3622. };
  3623. /**
  3624. * Retuns a new Quaternion set from the starting index of the passed array.
  3625. */
  3626. Quaternion.FromArray = function (array, offset) {
  3627. if (!offset) {
  3628. offset = 0;
  3629. }
  3630. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3631. };
  3632. /**
  3633. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3634. */
  3635. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3636. var q = new Quaternion();
  3637. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3638. return q;
  3639. };
  3640. /**
  3641. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3642. */
  3643. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3644. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3645. var halfRoll = roll * 0.5;
  3646. var halfPitch = pitch * 0.5;
  3647. var halfYaw = yaw * 0.5;
  3648. var sinRoll = Math.sin(halfRoll);
  3649. var cosRoll = Math.cos(halfRoll);
  3650. var sinPitch = Math.sin(halfPitch);
  3651. var cosPitch = Math.cos(halfPitch);
  3652. var sinYaw = Math.sin(halfYaw);
  3653. var cosYaw = Math.cos(halfYaw);
  3654. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3655. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3656. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3657. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3658. };
  3659. /**
  3660. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3661. */
  3662. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3663. var result = new Quaternion();
  3664. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3665. return result;
  3666. };
  3667. /**
  3668. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3669. */
  3670. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3671. // Produces a quaternion from Euler angles in the z-x-z orientation
  3672. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3673. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3674. var halfBeta = beta * 0.5;
  3675. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3676. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3677. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3678. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3679. };
  3680. /**
  3681. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3682. * cf to Vector3.RotationFromAxis() documentation.
  3683. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3684. */
  3685. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3686. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3687. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3688. return quat;
  3689. };
  3690. /**
  3691. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3692. * cf to Vector3.RotationFromAxis() documentation.
  3693. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3694. */
  3695. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3696. var rotMat = MathTmp.Matrix[0];
  3697. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3698. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3699. };
  3700. Quaternion.Slerp = function (left, right, amount) {
  3701. var result = Quaternion.Identity();
  3702. Quaternion.SlerpToRef(left, right, amount, result);
  3703. return result;
  3704. };
  3705. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3706. var num2;
  3707. var num3;
  3708. var num = amount;
  3709. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3710. var flag = false;
  3711. if (num4 < 0) {
  3712. flag = true;
  3713. num4 = -num4;
  3714. }
  3715. if (num4 > 0.999999) {
  3716. num3 = 1 - num;
  3717. num2 = flag ? -num : num;
  3718. }
  3719. else {
  3720. var num5 = Math.acos(num4);
  3721. var num6 = (1.0 / Math.sin(num5));
  3722. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3723. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3724. }
  3725. result.x = (num3 * left.x) + (num2 * right.x);
  3726. result.y = (num3 * left.y) + (num2 * right.y);
  3727. result.z = (num3 * left.z) + (num2 * right.z);
  3728. result.w = (num3 * left.w) + (num2 * right.w);
  3729. };
  3730. /**
  3731. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3732. */
  3733. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3734. var squared = amount * amount;
  3735. var cubed = amount * squared;
  3736. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3737. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3738. var part3 = (cubed - (2.0 * squared)) + amount;
  3739. var part4 = cubed - squared;
  3740. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3741. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3742. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3743. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3744. return new Quaternion(x, y, z, w);
  3745. };
  3746. return Quaternion;
  3747. }());
  3748. BABYLON.Quaternion = Quaternion;
  3749. var Matrix = /** @class */ (function () {
  3750. function Matrix() {
  3751. this._isIdentity = false;
  3752. this._isIdentityDirty = true;
  3753. this.m = new Float32Array(16);
  3754. this._markAsUpdated();
  3755. }
  3756. Matrix.prototype._markAsUpdated = function () {
  3757. this.updateFlag = Matrix._updateFlagSeed++;
  3758. this._isIdentityDirty = true;
  3759. };
  3760. // Properties
  3761. /**
  3762. * Boolean : True is the matrix is the identity matrix
  3763. */
  3764. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3765. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3766. if (this._isIdentityDirty) {
  3767. this._isIdentityDirty = false;
  3768. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3769. this._isIdentity = false;
  3770. }
  3771. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3772. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3773. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3774. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3775. this._isIdentity = false;
  3776. }
  3777. else {
  3778. this._isIdentity = true;
  3779. }
  3780. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3781. this._isIdentity = false;
  3782. }
  3783. }
  3784. return this._isIdentity;
  3785. };
  3786. /**
  3787. * Returns the matrix determinant (float).
  3788. */
  3789. Matrix.prototype.determinant = function () {
  3790. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3791. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3792. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3793. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3794. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3795. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3796. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3797. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3798. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3799. };
  3800. // Methods
  3801. /**
  3802. * Returns the matrix underlying array.
  3803. */
  3804. Matrix.prototype.toArray = function () {
  3805. return this.m;
  3806. };
  3807. /**
  3808. * Returns the matrix underlying array.
  3809. */
  3810. Matrix.prototype.asArray = function () {
  3811. return this.toArray();
  3812. };
  3813. /**
  3814. * Inverts in place the Matrix.
  3815. * Returns the Matrix inverted.
  3816. */
  3817. Matrix.prototype.invert = function () {
  3818. this.invertToRef(this);
  3819. return this;
  3820. };
  3821. /**
  3822. * Sets all the matrix elements to zero.
  3823. * Returns the Matrix.
  3824. */
  3825. Matrix.prototype.reset = function () {
  3826. for (var index = 0; index < 16; index++) {
  3827. this.m[index] = 0.0;
  3828. }
  3829. this._markAsUpdated();
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3834. */
  3835. Matrix.prototype.add = function (other) {
  3836. var result = new Matrix();
  3837. this.addToRef(other, result);
  3838. return result;
  3839. };
  3840. /**
  3841. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3842. * Returns the Matrix.
  3843. */
  3844. Matrix.prototype.addToRef = function (other, result) {
  3845. for (var index = 0; index < 16; index++) {
  3846. result.m[index] = this.m[index] + other.m[index];
  3847. }
  3848. result._markAsUpdated();
  3849. return this;
  3850. };
  3851. /**
  3852. * Adds in place the passed matrix to the current Matrix.
  3853. * Returns the updated Matrix.
  3854. */
  3855. Matrix.prototype.addToSelf = function (other) {
  3856. for (var index = 0; index < 16; index++) {
  3857. this.m[index] += other.m[index];
  3858. }
  3859. this._markAsUpdated();
  3860. return this;
  3861. };
  3862. /**
  3863. * Sets the passed matrix with the current inverted Matrix.
  3864. * Returns the unmodified current Matrix.
  3865. */
  3866. Matrix.prototype.invertToRef = function (other) {
  3867. var l1 = this.m[0];
  3868. var l2 = this.m[1];
  3869. var l3 = this.m[2];
  3870. var l4 = this.m[3];
  3871. var l5 = this.m[4];
  3872. var l6 = this.m[5];
  3873. var l7 = this.m[6];
  3874. var l8 = this.m[7];
  3875. var l9 = this.m[8];
  3876. var l10 = this.m[9];
  3877. var l11 = this.m[10];
  3878. var l12 = this.m[11];
  3879. var l13 = this.m[12];
  3880. var l14 = this.m[13];
  3881. var l15 = this.m[14];
  3882. var l16 = this.m[15];
  3883. var l17 = (l11 * l16) - (l12 * l15);
  3884. var l18 = (l10 * l16) - (l12 * l14);
  3885. var l19 = (l10 * l15) - (l11 * l14);
  3886. var l20 = (l9 * l16) - (l12 * l13);
  3887. var l21 = (l9 * l15) - (l11 * l13);
  3888. var l22 = (l9 * l14) - (l10 * l13);
  3889. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3890. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3891. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3892. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3893. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3894. var l28 = (l7 * l16) - (l8 * l15);
  3895. var l29 = (l6 * l16) - (l8 * l14);
  3896. var l30 = (l6 * l15) - (l7 * l14);
  3897. var l31 = (l5 * l16) - (l8 * l13);
  3898. var l32 = (l5 * l15) - (l7 * l13);
  3899. var l33 = (l5 * l14) - (l6 * l13);
  3900. var l34 = (l7 * l12) - (l8 * l11);
  3901. var l35 = (l6 * l12) - (l8 * l10);
  3902. var l36 = (l6 * l11) - (l7 * l10);
  3903. var l37 = (l5 * l12) - (l8 * l9);
  3904. var l38 = (l5 * l11) - (l7 * l9);
  3905. var l39 = (l5 * l10) - (l6 * l9);
  3906. other.m[0] = l23 * l27;
  3907. other.m[4] = l24 * l27;
  3908. other.m[8] = l25 * l27;
  3909. other.m[12] = l26 * l27;
  3910. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3911. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3912. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3913. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3914. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3915. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3916. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3917. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3918. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3919. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3920. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3921. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3922. other._markAsUpdated();
  3923. return this;
  3924. };
  3925. /**
  3926. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3927. * Returns the updated Matrix.
  3928. */
  3929. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3930. this.m[12] = x;
  3931. this.m[13] = y;
  3932. this.m[14] = z;
  3933. this._markAsUpdated();
  3934. return this;
  3935. };
  3936. /**
  3937. * Inserts the translation vector in the current Matrix.
  3938. * Returns the updated Matrix.
  3939. */
  3940. Matrix.prototype.setTranslation = function (vector3) {
  3941. this.m[12] = vector3.x;
  3942. this.m[13] = vector3.y;
  3943. this.m[14] = vector3.z;
  3944. this._markAsUpdated();
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector3 as the extracted translation from the Matrix.
  3949. */
  3950. Matrix.prototype.getTranslation = function () {
  3951. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3952. };
  3953. /**
  3954. * Fill a Vector3 with the extracted translation from the Matrix.
  3955. */
  3956. Matrix.prototype.getTranslationToRef = function (result) {
  3957. result.x = this.m[12];
  3958. result.y = this.m[13];
  3959. result.z = this.m[14];
  3960. return this;
  3961. };
  3962. /**
  3963. * Remove rotation and scaling part from the Matrix.
  3964. * Returns the updated Matrix.
  3965. */
  3966. Matrix.prototype.removeRotationAndScaling = function () {
  3967. this.setRowFromFloats(0, 1, 0, 0, 0);
  3968. this.setRowFromFloats(1, 0, 1, 0, 0);
  3969. this.setRowFromFloats(2, 0, 0, 1, 0);
  3970. return this;
  3971. };
  3972. /**
  3973. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3974. */
  3975. Matrix.prototype.multiply = function (other) {
  3976. var result = new Matrix();
  3977. this.multiplyToRef(other, result);
  3978. return result;
  3979. };
  3980. /**
  3981. * Updates the current Matrix from the passed one values.
  3982. * Returns the updated Matrix.
  3983. */
  3984. Matrix.prototype.copyFrom = function (other) {
  3985. for (var index = 0; index < 16; index++) {
  3986. this.m[index] = other.m[index];
  3987. }
  3988. this._markAsUpdated();
  3989. return this;
  3990. };
  3991. /**
  3992. * Populates the passed array from the starting index with the Matrix values.
  3993. * Returns the Matrix.
  3994. */
  3995. Matrix.prototype.copyToArray = function (array, offset) {
  3996. if (offset === void 0) { offset = 0; }
  3997. for (var index = 0; index < 16; index++) {
  3998. array[offset + index] = this.m[index];
  3999. }
  4000. return this;
  4001. };
  4002. /**
  4003. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4004. */
  4005. Matrix.prototype.multiplyToRef = function (other, result) {
  4006. this.multiplyToArray(other, result.m, 0);
  4007. result._markAsUpdated();
  4008. return this;
  4009. };
  4010. /**
  4011. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4012. */
  4013. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4014. var tm0 = this.m[0];
  4015. var tm1 = this.m[1];
  4016. var tm2 = this.m[2];
  4017. var tm3 = this.m[3];
  4018. var tm4 = this.m[4];
  4019. var tm5 = this.m[5];
  4020. var tm6 = this.m[6];
  4021. var tm7 = this.m[7];
  4022. var tm8 = this.m[8];
  4023. var tm9 = this.m[9];
  4024. var tm10 = this.m[10];
  4025. var tm11 = this.m[11];
  4026. var tm12 = this.m[12];
  4027. var tm13 = this.m[13];
  4028. var tm14 = this.m[14];
  4029. var tm15 = this.m[15];
  4030. var om0 = other.m[0];
  4031. var om1 = other.m[1];
  4032. var om2 = other.m[2];
  4033. var om3 = other.m[3];
  4034. var om4 = other.m[4];
  4035. var om5 = other.m[5];
  4036. var om6 = other.m[6];
  4037. var om7 = other.m[7];
  4038. var om8 = other.m[8];
  4039. var om9 = other.m[9];
  4040. var om10 = other.m[10];
  4041. var om11 = other.m[11];
  4042. var om12 = other.m[12];
  4043. var om13 = other.m[13];
  4044. var om14 = other.m[14];
  4045. var om15 = other.m[15];
  4046. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4047. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4048. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4049. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4050. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4051. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4052. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4053. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4054. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4055. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4056. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4057. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4058. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4059. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4060. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4061. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4062. return this;
  4063. };
  4064. /**
  4065. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4066. */
  4067. Matrix.prototype.equals = function (value) {
  4068. return value &&
  4069. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4070. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4071. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4072. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4073. };
  4074. /**
  4075. * Returns a new Matrix from the current Matrix.
  4076. */
  4077. Matrix.prototype.clone = function () {
  4078. 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]);
  4079. };
  4080. /**
  4081. * Returns the string "Matrix"
  4082. */
  4083. Matrix.prototype.getClassName = function () {
  4084. return "Matrix";
  4085. };
  4086. /**
  4087. * Returns the Matrix hash code.
  4088. */
  4089. Matrix.prototype.getHashCode = function () {
  4090. var hash = this.m[0] || 0;
  4091. for (var i = 1; i < 16; i++) {
  4092. hash = (hash * 397) ^ (this.m[i] || 0);
  4093. }
  4094. return hash;
  4095. };
  4096. /**
  4097. * Decomposes the current Matrix into :
  4098. * - a scale vector3 passed as a reference to update,
  4099. * - a rotation quaternion passed as a reference to update,
  4100. * - a translation vector3 passed as a reference to update.
  4101. * Returns the boolean `true`.
  4102. */
  4103. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4104. translation.x = this.m[12];
  4105. translation.y = this.m[13];
  4106. translation.z = this.m[14];
  4107. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4108. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4109. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4110. if (this.determinant() <= 0) {
  4111. scale.y *= -1;
  4112. }
  4113. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4114. rotation.x = 0;
  4115. rotation.y = 0;
  4116. rotation.z = 0;
  4117. rotation.w = 1;
  4118. return false;
  4119. }
  4120. 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]);
  4121. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4122. return true;
  4123. };
  4124. /**
  4125. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4126. */
  4127. Matrix.prototype.getRotationMatrix = function () {
  4128. var result = Matrix.Identity();
  4129. this.getRotationMatrixToRef(result);
  4130. return result;
  4131. };
  4132. /**
  4133. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4134. * Returns the current Matrix.
  4135. */
  4136. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4137. var m = this.m;
  4138. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4139. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4140. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4141. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4142. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4143. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4144. 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);
  4145. return this;
  4146. };
  4147. // Statics
  4148. /**
  4149. * Returns a new Matrix set from the starting index of the passed array.
  4150. */
  4151. Matrix.FromArray = function (array, offset) {
  4152. var result = new Matrix();
  4153. if (!offset) {
  4154. offset = 0;
  4155. }
  4156. Matrix.FromArrayToRef(array, offset, result);
  4157. return result;
  4158. };
  4159. /**
  4160. * Sets the passed "result" matrix from the starting index of the passed array.
  4161. */
  4162. Matrix.FromArrayToRef = function (array, offset, result) {
  4163. for (var index = 0; index < 16; index++) {
  4164. result.m[index] = array[index + offset];
  4165. }
  4166. result._markAsUpdated();
  4167. };
  4168. /**
  4169. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4170. */
  4171. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4172. for (var index = 0; index < 16; index++) {
  4173. result.m[index] = array[index + offset] * scale;
  4174. }
  4175. result._markAsUpdated();
  4176. };
  4177. /**
  4178. * Sets the passed matrix "result" with the 16 passed floats.
  4179. */
  4180. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4181. result.m[0] = initialM11;
  4182. result.m[1] = initialM12;
  4183. result.m[2] = initialM13;
  4184. result.m[3] = initialM14;
  4185. result.m[4] = initialM21;
  4186. result.m[5] = initialM22;
  4187. result.m[6] = initialM23;
  4188. result.m[7] = initialM24;
  4189. result.m[8] = initialM31;
  4190. result.m[9] = initialM32;
  4191. result.m[10] = initialM33;
  4192. result.m[11] = initialM34;
  4193. result.m[12] = initialM41;
  4194. result.m[13] = initialM42;
  4195. result.m[14] = initialM43;
  4196. result.m[15] = initialM44;
  4197. result._markAsUpdated();
  4198. };
  4199. /**
  4200. * Returns the index-th row of the current matrix as a new Vector4.
  4201. */
  4202. Matrix.prototype.getRow = function (index) {
  4203. if (index < 0 || index > 3) {
  4204. return null;
  4205. }
  4206. var i = index * 4;
  4207. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4208. };
  4209. /**
  4210. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4211. * Returns the updated Matrix.
  4212. */
  4213. Matrix.prototype.setRow = function (index, row) {
  4214. if (index < 0 || index > 3) {
  4215. return this;
  4216. }
  4217. var i = index * 4;
  4218. this.m[i + 0] = row.x;
  4219. this.m[i + 1] = row.y;
  4220. this.m[i + 2] = row.z;
  4221. this.m[i + 3] = row.w;
  4222. this._markAsUpdated();
  4223. return this;
  4224. };
  4225. /**
  4226. * Compute the transpose of the matrix.
  4227. * Returns a new Matrix.
  4228. */
  4229. Matrix.prototype.transpose = function () {
  4230. return Matrix.Transpose(this);
  4231. };
  4232. /**
  4233. * Compute the transpose of the matrix.
  4234. * Returns the current matrix.
  4235. */
  4236. Matrix.prototype.transposeToRef = function (result) {
  4237. Matrix.TransposeToRef(this, result);
  4238. return this;
  4239. };
  4240. /**
  4241. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4242. * Returns the updated Matrix.
  4243. */
  4244. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4245. if (index < 0 || index > 3) {
  4246. return this;
  4247. }
  4248. var i = index * 4;
  4249. this.m[i + 0] = x;
  4250. this.m[i + 1] = y;
  4251. this.m[i + 2] = z;
  4252. this.m[i + 3] = w;
  4253. this._markAsUpdated();
  4254. return this;
  4255. };
  4256. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4257. /**
  4258. * Static identity matrix to be used as readonly matrix
  4259. * Must not be updated.
  4260. */
  4261. get: function () {
  4262. return Matrix._identityReadOnly;
  4263. },
  4264. enumerable: true,
  4265. configurable: true
  4266. });
  4267. /**
  4268. * Returns a new Matrix set from the 16 passed floats.
  4269. */
  4270. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4271. var result = new Matrix();
  4272. result.m[0] = initialM11;
  4273. result.m[1] = initialM12;
  4274. result.m[2] = initialM13;
  4275. result.m[3] = initialM14;
  4276. result.m[4] = initialM21;
  4277. result.m[5] = initialM22;
  4278. result.m[6] = initialM23;
  4279. result.m[7] = initialM24;
  4280. result.m[8] = initialM31;
  4281. result.m[9] = initialM32;
  4282. result.m[10] = initialM33;
  4283. result.m[11] = initialM34;
  4284. result.m[12] = initialM41;
  4285. result.m[13] = initialM42;
  4286. result.m[14] = initialM43;
  4287. result.m[15] = initialM44;
  4288. return result;
  4289. };
  4290. /**
  4291. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4292. */
  4293. Matrix.Compose = function (scale, rotation, translation) {
  4294. var result = Matrix.Identity();
  4295. Matrix.ComposeToRef(scale, rotation, translation, result);
  4296. return result;
  4297. };
  4298. /**
  4299. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4300. */
  4301. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4302. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4303. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4304. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4305. result.setTranslation(translation);
  4306. };
  4307. /**
  4308. * Returns a new indentity Matrix.
  4309. */
  4310. Matrix.Identity = function () {
  4311. 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);
  4312. };
  4313. /**
  4314. * Sets the passed "result" as an identity matrix.
  4315. */
  4316. Matrix.IdentityToRef = function (result) {
  4317. 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);
  4318. };
  4319. /**
  4320. * Returns a new zero Matrix.
  4321. */
  4322. Matrix.Zero = function () {
  4323. 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);
  4324. };
  4325. /**
  4326. * Returns a new rotation matrix for "angle" radians around the X axis.
  4327. */
  4328. Matrix.RotationX = function (angle) {
  4329. var result = new Matrix();
  4330. Matrix.RotationXToRef(angle, result);
  4331. return result;
  4332. };
  4333. /**
  4334. * Returns a new Matrix as the passed inverted one.
  4335. */
  4336. Matrix.Invert = function (source) {
  4337. var result = new Matrix();
  4338. source.invertToRef(result);
  4339. return result;
  4340. };
  4341. /**
  4342. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4343. */
  4344. Matrix.RotationXToRef = function (angle, result) {
  4345. var s = Math.sin(angle);
  4346. var c = Math.cos(angle);
  4347. result.m[0] = 1.0;
  4348. result.m[15] = 1.0;
  4349. result.m[5] = c;
  4350. result.m[10] = c;
  4351. result.m[9] = -s;
  4352. result.m[6] = s;
  4353. result.m[1] = 0.0;
  4354. result.m[2] = 0.0;
  4355. result.m[3] = 0.0;
  4356. result.m[4] = 0.0;
  4357. result.m[7] = 0.0;
  4358. result.m[8] = 0.0;
  4359. result.m[11] = 0.0;
  4360. result.m[12] = 0.0;
  4361. result.m[13] = 0.0;
  4362. result.m[14] = 0.0;
  4363. result._markAsUpdated();
  4364. };
  4365. /**
  4366. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4367. */
  4368. Matrix.RotationY = function (angle) {
  4369. var result = new Matrix();
  4370. Matrix.RotationYToRef(angle, result);
  4371. return result;
  4372. };
  4373. /**
  4374. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4375. */
  4376. Matrix.RotationYToRef = function (angle, result) {
  4377. var s = Math.sin(angle);
  4378. var c = Math.cos(angle);
  4379. result.m[5] = 1.0;
  4380. result.m[15] = 1.0;
  4381. result.m[0] = c;
  4382. result.m[2] = -s;
  4383. result.m[8] = s;
  4384. result.m[10] = c;
  4385. result.m[1] = 0.0;
  4386. result.m[3] = 0.0;
  4387. result.m[4] = 0.0;
  4388. result.m[6] = 0.0;
  4389. result.m[7] = 0.0;
  4390. result.m[9] = 0.0;
  4391. result.m[11] = 0.0;
  4392. result.m[12] = 0.0;
  4393. result.m[13] = 0.0;
  4394. result.m[14] = 0.0;
  4395. result._markAsUpdated();
  4396. };
  4397. /**
  4398. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4399. */
  4400. Matrix.RotationZ = function (angle) {
  4401. var result = new Matrix();
  4402. Matrix.RotationZToRef(angle, result);
  4403. return result;
  4404. };
  4405. /**
  4406. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4407. */
  4408. Matrix.RotationZToRef = function (angle, result) {
  4409. var s = Math.sin(angle);
  4410. var c = Math.cos(angle);
  4411. result.m[10] = 1.0;
  4412. result.m[15] = 1.0;
  4413. result.m[0] = c;
  4414. result.m[1] = s;
  4415. result.m[4] = -s;
  4416. result.m[5] = c;
  4417. result.m[2] = 0.0;
  4418. result.m[3] = 0.0;
  4419. result.m[6] = 0.0;
  4420. result.m[7] = 0.0;
  4421. result.m[8] = 0.0;
  4422. result.m[9] = 0.0;
  4423. result.m[11] = 0.0;
  4424. result.m[12] = 0.0;
  4425. result.m[13] = 0.0;
  4426. result.m[14] = 0.0;
  4427. result._markAsUpdated();
  4428. };
  4429. /**
  4430. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4431. */
  4432. Matrix.RotationAxis = function (axis, angle) {
  4433. var result = Matrix.Zero();
  4434. Matrix.RotationAxisToRef(axis, angle, result);
  4435. return result;
  4436. };
  4437. /**
  4438. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4439. */
  4440. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4441. var s = Math.sin(-angle);
  4442. var c = Math.cos(-angle);
  4443. var c1 = 1 - c;
  4444. axis.normalize();
  4445. result.m[0] = (axis.x * axis.x) * c1 + c;
  4446. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4447. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4448. result.m[3] = 0.0;
  4449. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4450. result.m[5] = (axis.y * axis.y) * c1 + c;
  4451. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4452. result.m[7] = 0.0;
  4453. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4454. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4455. result.m[10] = (axis.z * axis.z) * c1 + c;
  4456. result.m[11] = 0.0;
  4457. result.m[15] = 1.0;
  4458. result._markAsUpdated();
  4459. };
  4460. /**
  4461. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4462. */
  4463. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4464. var result = new Matrix();
  4465. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4466. return result;
  4467. };
  4468. /**
  4469. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4470. */
  4471. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4472. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4473. this._tempQuaternion.toRotationMatrix(result);
  4474. };
  4475. /**
  4476. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4477. */
  4478. Matrix.Scaling = function (x, y, z) {
  4479. var result = Matrix.Zero();
  4480. Matrix.ScalingToRef(x, y, z, result);
  4481. return result;
  4482. };
  4483. /**
  4484. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4485. */
  4486. Matrix.ScalingToRef = function (x, y, z, result) {
  4487. result.m[0] = x;
  4488. result.m[1] = 0.0;
  4489. result.m[2] = 0.0;
  4490. result.m[3] = 0.0;
  4491. result.m[4] = 0.0;
  4492. result.m[5] = y;
  4493. result.m[6] = 0.0;
  4494. result.m[7] = 0.0;
  4495. result.m[8] = 0.0;
  4496. result.m[9] = 0.0;
  4497. result.m[10] = z;
  4498. result.m[11] = 0.0;
  4499. result.m[12] = 0.0;
  4500. result.m[13] = 0.0;
  4501. result.m[14] = 0.0;
  4502. result.m[15] = 1.0;
  4503. result._markAsUpdated();
  4504. };
  4505. /**
  4506. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4507. */
  4508. Matrix.Translation = function (x, y, z) {
  4509. var result = Matrix.Identity();
  4510. Matrix.TranslationToRef(x, y, z, result);
  4511. return result;
  4512. };
  4513. /**
  4514. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4515. */
  4516. Matrix.TranslationToRef = function (x, y, z, result) {
  4517. 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);
  4518. };
  4519. /**
  4520. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4521. */
  4522. Matrix.Lerp = function (startValue, endValue, gradient) {
  4523. var result = Matrix.Zero();
  4524. for (var index = 0; index < 16; index++) {
  4525. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4526. }
  4527. result._markAsUpdated();
  4528. return result;
  4529. };
  4530. /**
  4531. * Returns a new Matrix whose values are computed by :
  4532. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4533. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4534. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4535. */
  4536. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4537. var startScale = new Vector3(0, 0, 0);
  4538. var startRotation = new Quaternion();
  4539. var startTranslation = new Vector3(0, 0, 0);
  4540. startValue.decompose(startScale, startRotation, startTranslation);
  4541. var endScale = new Vector3(0, 0, 0);
  4542. var endRotation = new Quaternion();
  4543. var endTranslation = new Vector3(0, 0, 0);
  4544. endValue.decompose(endScale, endRotation, endTranslation);
  4545. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4546. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4547. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4548. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4549. };
  4550. /**
  4551. * 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".
  4552. * This methods works for a Left-Handed system.
  4553. */
  4554. Matrix.LookAtLH = function (eye, target, up) {
  4555. var result = Matrix.Zero();
  4556. Matrix.LookAtLHToRef(eye, target, up, result);
  4557. return result;
  4558. };
  4559. /**
  4560. * 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".
  4561. * This methods works for a Left-Handed system.
  4562. */
  4563. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4564. // Z axis
  4565. target.subtractToRef(eye, this._zAxis);
  4566. this._zAxis.normalize();
  4567. // X axis
  4568. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4569. if (this._xAxis.lengthSquared() === 0) {
  4570. this._xAxis.x = 1.0;
  4571. }
  4572. else {
  4573. this._xAxis.normalize();
  4574. }
  4575. // Y axis
  4576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4577. this._yAxis.normalize();
  4578. // Eye angles
  4579. var ex = -Vector3.Dot(this._xAxis, eye);
  4580. var ey = -Vector3.Dot(this._yAxis, eye);
  4581. var ez = -Vector3.Dot(this._zAxis, eye);
  4582. 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);
  4583. };
  4584. /**
  4585. * 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".
  4586. * This methods works for a Right-Handed system.
  4587. */
  4588. Matrix.LookAtRH = function (eye, target, up) {
  4589. var result = Matrix.Zero();
  4590. Matrix.LookAtRHToRef(eye, target, up, result);
  4591. return result;
  4592. };
  4593. /**
  4594. * 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".
  4595. * This methods works for a Left-Handed system.
  4596. */
  4597. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4598. // Z axis
  4599. eye.subtractToRef(target, this._zAxis);
  4600. this._zAxis.normalize();
  4601. // X axis
  4602. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4603. if (this._xAxis.lengthSquared() === 0) {
  4604. this._xAxis.x = 1.0;
  4605. }
  4606. else {
  4607. this._xAxis.normalize();
  4608. }
  4609. // Y axis
  4610. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4611. this._yAxis.normalize();
  4612. // Eye angles
  4613. var ex = -Vector3.Dot(this._xAxis, eye);
  4614. var ey = -Vector3.Dot(this._yAxis, eye);
  4615. var ez = -Vector3.Dot(this._zAxis, eye);
  4616. 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);
  4617. };
  4618. /**
  4619. * 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.
  4620. */
  4621. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4622. var matrix = Matrix.Zero();
  4623. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4624. return matrix;
  4625. };
  4626. /**
  4627. * 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.
  4628. */
  4629. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4630. var n = znear;
  4631. var f = zfar;
  4632. var a = 2.0 / width;
  4633. var b = 2.0 / height;
  4634. var c = 2.0 / (f - n);
  4635. var d = -(f + n) / (f - n);
  4636. 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);
  4637. };
  4638. /**
  4639. * 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.
  4640. */
  4641. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4642. var matrix = Matrix.Zero();
  4643. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4644. return matrix;
  4645. };
  4646. /**
  4647. * 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.
  4648. */
  4649. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4650. var n = znear;
  4651. var f = zfar;
  4652. var a = 2.0 / (right - left);
  4653. var b = 2.0 / (top - bottom);
  4654. var c = 2.0 / (f - n);
  4655. var d = -(f + n) / (f - n);
  4656. var i0 = (left + right) / (left - right);
  4657. var i1 = (top + bottom) / (bottom - top);
  4658. 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);
  4659. };
  4660. /**
  4661. * 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.
  4662. */
  4663. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4664. var matrix = Matrix.Zero();
  4665. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4666. return matrix;
  4667. };
  4668. /**
  4669. * 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.
  4670. */
  4671. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4672. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4673. result.m[10] *= -1.0;
  4674. };
  4675. /**
  4676. * 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.
  4677. */
  4678. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4679. var matrix = Matrix.Zero();
  4680. var n = znear;
  4681. var f = zfar;
  4682. var a = 2.0 * n / width;
  4683. var b = 2.0 * n / height;
  4684. var c = (f + n) / (f - n);
  4685. var d = -2.0 * f * n / (f - n);
  4686. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  4687. return matrix;
  4688. };
  4689. /**
  4690. * 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.
  4691. */
  4692. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4693. var matrix = Matrix.Zero();
  4694. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4695. return matrix;
  4696. };
  4697. /**
  4698. * 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.
  4699. */
  4700. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4701. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4702. var n = znear;
  4703. var f = zfar;
  4704. var t = 1.0 / (Math.tan(fov * 0.5));
  4705. var a = isVerticalFovFixed ? (t / aspect) : t;
  4706. var b = isVerticalFovFixed ? t : (t * aspect);
  4707. var c = (f + n) / (f - n);
  4708. var d = -2.0 * f * n / (f - n);
  4709. 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);
  4710. };
  4711. /**
  4712. * 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.
  4713. */
  4714. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4715. var matrix = Matrix.Zero();
  4716. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4717. return matrix;
  4718. };
  4719. /**
  4720. * 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.
  4721. */
  4722. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4723. //alternatively this could be expressed as:
  4724. // m = PerspectiveFovLHToRef
  4725. // m[10] *= -1.0;
  4726. // m[11] *= -1.0;
  4727. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4728. var n = znear;
  4729. var f = zfar;
  4730. var t = 1.0 / (Math.tan(fov * 0.5));
  4731. var a = isVerticalFovFixed ? (t / aspect) : t;
  4732. var b = isVerticalFovFixed ? t : (t * aspect);
  4733. var c = -(f + n) / (f - n);
  4734. var d = -2 * f * n / (f - n);
  4735. 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);
  4736. };
  4737. /**
  4738. * 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.
  4739. */
  4740. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4741. if (rightHanded === void 0) { rightHanded = false; }
  4742. var rightHandedFactor = rightHanded ? -1 : 1;
  4743. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4744. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4745. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4746. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4747. var xScale = 2.0 / (leftTan + rightTan);
  4748. var yScale = 2.0 / (upTan + downTan);
  4749. result.m[0] = xScale;
  4750. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4751. result.m[5] = yScale;
  4752. result.m[6] = result.m[7] = 0.0;
  4753. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4754. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4755. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4756. result.m[10] = -zfar / (znear - zfar);
  4757. result.m[11] = 1.0 * rightHandedFactor;
  4758. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4759. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4760. // result.m[14] = (znear * zfar) / (znear - zfar);
  4761. result._markAsUpdated();
  4762. };
  4763. /**
  4764. * Returns the final transformation matrix : world * view * projection * viewport
  4765. */
  4766. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4767. var cw = viewport.width;
  4768. var ch = viewport.height;
  4769. var cx = viewport.x;
  4770. var cy = viewport.y;
  4771. 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);
  4772. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4773. };
  4774. /**
  4775. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4776. */
  4777. Matrix.GetAsMatrix2x2 = function (matrix) {
  4778. return new Float32Array([
  4779. matrix.m[0], matrix.m[1],
  4780. matrix.m[4], matrix.m[5]
  4781. ]);
  4782. };
  4783. /**
  4784. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4785. */
  4786. Matrix.GetAsMatrix3x3 = function (matrix) {
  4787. return new Float32Array([
  4788. matrix.m[0], matrix.m[1], matrix.m[2],
  4789. matrix.m[4], matrix.m[5], matrix.m[6],
  4790. matrix.m[8], matrix.m[9], matrix.m[10]
  4791. ]);
  4792. };
  4793. /**
  4794. * Compute the transpose of the passed Matrix.
  4795. * Returns a new Matrix.
  4796. */
  4797. Matrix.Transpose = function (matrix) {
  4798. var result = new Matrix();
  4799. Matrix.TransposeToRef(matrix, result);
  4800. return result;
  4801. };
  4802. /**
  4803. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4804. */
  4805. Matrix.TransposeToRef = function (matrix, result) {
  4806. result.m[0] = matrix.m[0];
  4807. result.m[1] = matrix.m[4];
  4808. result.m[2] = matrix.m[8];
  4809. result.m[3] = matrix.m[12];
  4810. result.m[4] = matrix.m[1];
  4811. result.m[5] = matrix.m[5];
  4812. result.m[6] = matrix.m[9];
  4813. result.m[7] = matrix.m[13];
  4814. result.m[8] = matrix.m[2];
  4815. result.m[9] = matrix.m[6];
  4816. result.m[10] = matrix.m[10];
  4817. result.m[11] = matrix.m[14];
  4818. result.m[12] = matrix.m[3];
  4819. result.m[13] = matrix.m[7];
  4820. result.m[14] = matrix.m[11];
  4821. result.m[15] = matrix.m[15];
  4822. };
  4823. /**
  4824. * Returns a new Matrix as the reflection matrix across the passed plane.
  4825. */
  4826. Matrix.Reflection = function (plane) {
  4827. var matrix = new Matrix();
  4828. Matrix.ReflectionToRef(plane, matrix);
  4829. return matrix;
  4830. };
  4831. /**
  4832. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4833. */
  4834. Matrix.ReflectionToRef = function (plane, result) {
  4835. plane.normalize();
  4836. var x = plane.normal.x;
  4837. var y = plane.normal.y;
  4838. var z = plane.normal.z;
  4839. var temp = -2 * x;
  4840. var temp2 = -2 * y;
  4841. var temp3 = -2 * z;
  4842. result.m[0] = (temp * x) + 1;
  4843. result.m[1] = temp2 * x;
  4844. result.m[2] = temp3 * x;
  4845. result.m[3] = 0.0;
  4846. result.m[4] = temp * y;
  4847. result.m[5] = (temp2 * y) + 1;
  4848. result.m[6] = temp3 * y;
  4849. result.m[7] = 0.0;
  4850. result.m[8] = temp * z;
  4851. result.m[9] = temp2 * z;
  4852. result.m[10] = (temp3 * z) + 1;
  4853. result.m[11] = 0.0;
  4854. result.m[12] = temp * plane.d;
  4855. result.m[13] = temp2 * plane.d;
  4856. result.m[14] = temp3 * plane.d;
  4857. result.m[15] = 1.0;
  4858. result._markAsUpdated();
  4859. };
  4860. /**
  4861. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4862. */
  4863. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4864. result.m[0] = xaxis.x;
  4865. result.m[1] = xaxis.y;
  4866. result.m[2] = xaxis.z;
  4867. result.m[3] = 0.0;
  4868. result.m[4] = yaxis.x;
  4869. result.m[5] = yaxis.y;
  4870. result.m[6] = yaxis.z;
  4871. result.m[7] = 0.0;
  4872. result.m[8] = zaxis.x;
  4873. result.m[9] = zaxis.y;
  4874. result.m[10] = zaxis.z;
  4875. result.m[11] = 0.0;
  4876. result.m[12] = 0.0;
  4877. result.m[13] = 0.0;
  4878. result.m[14] = 0.0;
  4879. result.m[15] = 1.0;
  4880. result._markAsUpdated();
  4881. };
  4882. /**
  4883. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4884. */
  4885. Matrix.FromQuaternionToRef = function (quat, result) {
  4886. var xx = quat.x * quat.x;
  4887. var yy = quat.y * quat.y;
  4888. var zz = quat.z * quat.z;
  4889. var xy = quat.x * quat.y;
  4890. var zw = quat.z * quat.w;
  4891. var zx = quat.z * quat.x;
  4892. var yw = quat.y * quat.w;
  4893. var yz = quat.y * quat.z;
  4894. var xw = quat.x * quat.w;
  4895. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4896. result.m[1] = 2.0 * (xy + zw);
  4897. result.m[2] = 2.0 * (zx - yw);
  4898. result.m[3] = 0.0;
  4899. result.m[4] = 2.0 * (xy - zw);
  4900. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4901. result.m[6] = 2.0 * (yz + xw);
  4902. result.m[7] = 0.0;
  4903. result.m[8] = 2.0 * (zx + yw);
  4904. result.m[9] = 2.0 * (yz - xw);
  4905. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4906. result.m[11] = 0.0;
  4907. result.m[12] = 0.0;
  4908. result.m[13] = 0.0;
  4909. result.m[14] = 0.0;
  4910. result.m[15] = 1.0;
  4911. result._markAsUpdated();
  4912. };
  4913. Matrix._tempQuaternion = new Quaternion();
  4914. Matrix._xAxis = Vector3.Zero();
  4915. Matrix._yAxis = Vector3.Zero();
  4916. Matrix._zAxis = Vector3.Zero();
  4917. Matrix._updateFlagSeed = 0;
  4918. Matrix._identityReadOnly = Matrix.Identity();
  4919. return Matrix;
  4920. }());
  4921. BABYLON.Matrix = Matrix;
  4922. var Plane = /** @class */ (function () {
  4923. /**
  4924. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4925. */
  4926. function Plane(a, b, c, d) {
  4927. this.normal = new Vector3(a, b, c);
  4928. this.d = d;
  4929. }
  4930. /**
  4931. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4932. */
  4933. Plane.prototype.asArray = function () {
  4934. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4935. };
  4936. // Methods
  4937. /**
  4938. * Returns a new plane copied from the current Plane.
  4939. */
  4940. Plane.prototype.clone = function () {
  4941. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4942. };
  4943. /**
  4944. * Returns the string "Plane".
  4945. */
  4946. Plane.prototype.getClassName = function () {
  4947. return "Plane";
  4948. };
  4949. /**
  4950. * Returns the Plane hash code.
  4951. */
  4952. Plane.prototype.getHashCode = function () {
  4953. var hash = this.normal.getHashCode();
  4954. hash = (hash * 397) ^ (this.d || 0);
  4955. return hash;
  4956. };
  4957. /**
  4958. * Normalize the current Plane in place.
  4959. * Returns the updated Plane.
  4960. */
  4961. Plane.prototype.normalize = function () {
  4962. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4963. var magnitude = 0.0;
  4964. if (norm !== 0) {
  4965. magnitude = 1.0 / norm;
  4966. }
  4967. this.normal.x *= magnitude;
  4968. this.normal.y *= magnitude;
  4969. this.normal.z *= magnitude;
  4970. this.d *= magnitude;
  4971. return this;
  4972. };
  4973. /**
  4974. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4975. */
  4976. Plane.prototype.transform = function (transformation) {
  4977. var transposedMatrix = Matrix.Transpose(transformation);
  4978. var x = this.normal.x;
  4979. var y = this.normal.y;
  4980. var z = this.normal.z;
  4981. var d = this.d;
  4982. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4983. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4984. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4985. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4986. return new Plane(normalX, normalY, normalZ, finalD);
  4987. };
  4988. /**
  4989. * Returns the dot product (float) of the point coordinates and the plane normal.
  4990. */
  4991. Plane.prototype.dotCoordinate = function (point) {
  4992. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4993. };
  4994. /**
  4995. * Updates the current Plane from the plane defined by the three passed points.
  4996. * Returns the updated Plane.
  4997. */
  4998. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4999. var x1 = point2.x - point1.x;
  5000. var y1 = point2.y - point1.y;
  5001. var z1 = point2.z - point1.z;
  5002. var x2 = point3.x - point1.x;
  5003. var y2 = point3.y - point1.y;
  5004. var z2 = point3.z - point1.z;
  5005. var yz = (y1 * z2) - (z1 * y2);
  5006. var xz = (z1 * x2) - (x1 * z2);
  5007. var xy = (x1 * y2) - (y1 * x2);
  5008. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5009. var invPyth;
  5010. if (pyth !== 0) {
  5011. invPyth = 1.0 / pyth;
  5012. }
  5013. else {
  5014. invPyth = 0.0;
  5015. }
  5016. this.normal.x = yz * invPyth;
  5017. this.normal.y = xz * invPyth;
  5018. this.normal.z = xy * invPyth;
  5019. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5020. return this;
  5021. };
  5022. /**
  5023. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5024. */
  5025. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5026. var dot = Vector3.Dot(this.normal, direction);
  5027. return (dot <= epsilon);
  5028. };
  5029. /**
  5030. * Returns the signed distance (float) from the passed point to the Plane.
  5031. */
  5032. Plane.prototype.signedDistanceTo = function (point) {
  5033. return Vector3.Dot(point, this.normal) + this.d;
  5034. };
  5035. // Statics
  5036. /**
  5037. * Returns a new Plane from the passed array.
  5038. */
  5039. Plane.FromArray = function (array) {
  5040. return new Plane(array[0], array[1], array[2], array[3]);
  5041. };
  5042. /**
  5043. * Returns a new Plane defined by the three passed points.
  5044. */
  5045. Plane.FromPoints = function (point1, point2, point3) {
  5046. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5047. result.copyFromPoints(point1, point2, point3);
  5048. return result;
  5049. };
  5050. /**
  5051. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5052. * Note : the vector "normal" is updated because normalized.
  5053. */
  5054. Plane.FromPositionAndNormal = function (origin, normal) {
  5055. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5056. normal.normalize();
  5057. result.normal = normal;
  5058. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5059. return result;
  5060. };
  5061. /**
  5062. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5063. */
  5064. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5065. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5066. return Vector3.Dot(point, normal) + d;
  5067. };
  5068. return Plane;
  5069. }());
  5070. BABYLON.Plane = Plane;
  5071. var Viewport = /** @class */ (function () {
  5072. /**
  5073. * Creates a Viewport object located at (x, y) and sized (width, height).
  5074. */
  5075. function Viewport(x, y, width, height) {
  5076. this.x = x;
  5077. this.y = y;
  5078. this.width = width;
  5079. this.height = height;
  5080. }
  5081. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5082. if (renderWidthOrEngine.getRenderWidth) {
  5083. var engine = renderWidthOrEngine;
  5084. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5085. }
  5086. var renderWidth = renderWidthOrEngine;
  5087. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5088. };
  5089. /**
  5090. * Returns a new Viewport copied from the current one.
  5091. */
  5092. Viewport.prototype.clone = function () {
  5093. return new Viewport(this.x, this.y, this.width, this.height);
  5094. };
  5095. return Viewport;
  5096. }());
  5097. BABYLON.Viewport = Viewport;
  5098. var Frustum = /** @class */ (function () {
  5099. function Frustum() {
  5100. }
  5101. /**
  5102. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5103. */
  5104. Frustum.GetPlanes = function (transform) {
  5105. var frustumPlanes = [];
  5106. for (var index = 0; index < 6; index++) {
  5107. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5108. }
  5109. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5110. return frustumPlanes;
  5111. };
  5112. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5113. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5114. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5115. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5116. frustumPlane.d = transform.m[15] + transform.m[14];
  5117. frustumPlane.normalize();
  5118. };
  5119. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5120. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5121. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5122. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5123. frustumPlane.d = transform.m[15] - transform.m[14];
  5124. frustumPlane.normalize();
  5125. };
  5126. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5127. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5128. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5129. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5130. frustumPlane.d = transform.m[15] + transform.m[12];
  5131. frustumPlane.normalize();
  5132. };
  5133. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5134. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5135. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5136. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5137. frustumPlane.d = transform.m[15] - transform.m[12];
  5138. frustumPlane.normalize();
  5139. };
  5140. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5141. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5142. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5143. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5144. frustumPlane.d = transform.m[15] - transform.m[13];
  5145. frustumPlane.normalize();
  5146. };
  5147. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5148. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5149. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5150. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5151. frustumPlane.d = transform.m[15] + transform.m[13];
  5152. frustumPlane.normalize();
  5153. };
  5154. /**
  5155. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5156. */
  5157. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5158. // Near
  5159. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5160. // Far
  5161. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5162. // Left
  5163. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5164. // Right
  5165. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5166. // Top
  5167. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5168. // Bottom
  5169. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5170. };
  5171. return Frustum;
  5172. }());
  5173. BABYLON.Frustum = Frustum;
  5174. var Space;
  5175. (function (Space) {
  5176. Space[Space["LOCAL"] = 0] = "LOCAL";
  5177. Space[Space["WORLD"] = 1] = "WORLD";
  5178. Space[Space["BONE"] = 2] = "BONE";
  5179. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5180. var Axis = /** @class */ (function () {
  5181. function Axis() {
  5182. }
  5183. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5184. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5185. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5186. return Axis;
  5187. }());
  5188. BABYLON.Axis = Axis;
  5189. ;
  5190. var BezierCurve = /** @class */ (function () {
  5191. function BezierCurve() {
  5192. }
  5193. /**
  5194. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5195. */
  5196. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5197. // Extract X (which is equal to time here)
  5198. var f0 = 1 - 3 * x2 + 3 * x1;
  5199. var f1 = 3 * x2 - 6 * x1;
  5200. var f2 = 3 * x1;
  5201. var refinedT = t;
  5202. for (var i = 0; i < 5; i++) {
  5203. var refinedT2 = refinedT * refinedT;
  5204. var refinedT3 = refinedT2 * refinedT;
  5205. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5206. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5207. refinedT -= (x - t) * slope;
  5208. refinedT = Math.min(1, Math.max(0, refinedT));
  5209. }
  5210. // Resolve cubic bezier for the given x
  5211. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5212. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5213. Math.pow(refinedT, 3);
  5214. };
  5215. return BezierCurve;
  5216. }());
  5217. BABYLON.BezierCurve = BezierCurve;
  5218. var Orientation;
  5219. (function (Orientation) {
  5220. Orientation[Orientation["CW"] = 0] = "CW";
  5221. Orientation[Orientation["CCW"] = 1] = "CCW";
  5222. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5223. var Angle = /** @class */ (function () {
  5224. /**
  5225. * Creates an Angle object of "radians" radians (float).
  5226. */
  5227. function Angle(radians) {
  5228. var _this = this;
  5229. /**
  5230. * Returns the Angle value in degrees (float).
  5231. */
  5232. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5233. /**
  5234. * Returns the Angle value in radians (float).
  5235. */
  5236. this.radians = function () { return _this._radians; };
  5237. this._radians = radians;
  5238. if (this._radians < 0.0)
  5239. this._radians += (2.0 * Math.PI);
  5240. }
  5241. /**
  5242. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5243. */
  5244. Angle.BetweenTwoPoints = function (a, b) {
  5245. var delta = b.subtract(a);
  5246. var theta = Math.atan2(delta.y, delta.x);
  5247. return new Angle(theta);
  5248. };
  5249. /**
  5250. * Returns a new Angle object from the passed float in radians.
  5251. */
  5252. Angle.FromRadians = function (radians) {
  5253. return new Angle(radians);
  5254. };
  5255. /**
  5256. * Returns a new Angle object from the passed float in degrees.
  5257. */
  5258. Angle.FromDegrees = function (degrees) {
  5259. return new Angle(degrees * Math.PI / 180.0);
  5260. };
  5261. return Angle;
  5262. }());
  5263. BABYLON.Angle = Angle;
  5264. var Arc2 = /** @class */ (function () {
  5265. /**
  5266. * Creates an Arc object from the three passed points : start, middle and end.
  5267. */
  5268. function Arc2(startPoint, midPoint, endPoint) {
  5269. this.startPoint = startPoint;
  5270. this.midPoint = midPoint;
  5271. this.endPoint = endPoint;
  5272. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5273. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5274. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5275. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5276. 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);
  5277. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5278. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5279. var a1 = this.startAngle.degrees();
  5280. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5281. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5282. // angles correction
  5283. if (a2 - a1 > +180.0)
  5284. a2 -= 360.0;
  5285. if (a2 - a1 < -180.0)
  5286. a2 += 360.0;
  5287. if (a3 - a2 > +180.0)
  5288. a3 -= 360.0;
  5289. if (a3 - a2 < -180.0)
  5290. a3 += 360.0;
  5291. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5292. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5293. }
  5294. return Arc2;
  5295. }());
  5296. BABYLON.Arc2 = Arc2;
  5297. var Path2 = /** @class */ (function () {
  5298. /**
  5299. * Creates a Path2 object from the starting 2D coordinates x and y.
  5300. */
  5301. function Path2(x, y) {
  5302. this._points = new Array();
  5303. this._length = 0.0;
  5304. this.closed = false;
  5305. this._points.push(new Vector2(x, y));
  5306. }
  5307. /**
  5308. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5309. * Returns the updated Path2.
  5310. */
  5311. Path2.prototype.addLineTo = function (x, y) {
  5312. if (this.closed) {
  5313. //Tools.Error("cannot add lines to closed paths");
  5314. return this;
  5315. }
  5316. var newPoint = new Vector2(x, y);
  5317. var previousPoint = this._points[this._points.length - 1];
  5318. this._points.push(newPoint);
  5319. this._length += newPoint.subtract(previousPoint).length();
  5320. return this;
  5321. };
  5322. /**
  5323. * 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.
  5324. * Returns the updated Path2.
  5325. */
  5326. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5327. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5328. if (this.closed) {
  5329. //Tools.Error("cannot add arcs to closed paths");
  5330. return this;
  5331. }
  5332. var startPoint = this._points[this._points.length - 1];
  5333. var midPoint = new Vector2(midX, midY);
  5334. var endPoint = new Vector2(endX, endY);
  5335. var arc = new Arc2(startPoint, midPoint, endPoint);
  5336. var increment = arc.angle.radians() / numberOfSegments;
  5337. if (arc.orientation === Orientation.CW)
  5338. increment *= -1;
  5339. var currentAngle = arc.startAngle.radians() + increment;
  5340. for (var i = 0; i < numberOfSegments; i++) {
  5341. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5342. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5343. this.addLineTo(x, y);
  5344. currentAngle += increment;
  5345. }
  5346. return this;
  5347. };
  5348. /**
  5349. * Closes the Path2.
  5350. * Returns the Path2.
  5351. */
  5352. Path2.prototype.close = function () {
  5353. this.closed = true;
  5354. return this;
  5355. };
  5356. /**
  5357. * Returns the Path2 total length (float).
  5358. */
  5359. Path2.prototype.length = function () {
  5360. var result = this._length;
  5361. if (!this.closed) {
  5362. var lastPoint = this._points[this._points.length - 1];
  5363. var firstPoint = this._points[0];
  5364. result += (firstPoint.subtract(lastPoint).length());
  5365. }
  5366. return result;
  5367. };
  5368. /**
  5369. * Returns the Path2 internal array of points.
  5370. */
  5371. Path2.prototype.getPoints = function () {
  5372. return this._points;
  5373. };
  5374. /**
  5375. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5376. */
  5377. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5378. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5379. //Tools.Error("normalized length position should be between 0 and 1.");
  5380. return Vector2.Zero();
  5381. }
  5382. var lengthPosition = normalizedLengthPosition * this.length();
  5383. var previousOffset = 0;
  5384. for (var i = 0; i < this._points.length; i++) {
  5385. var j = (i + 1) % this._points.length;
  5386. var a = this._points[i];
  5387. var b = this._points[j];
  5388. var bToA = b.subtract(a);
  5389. var nextOffset = (bToA.length() + previousOffset);
  5390. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5391. var dir = bToA.normalize();
  5392. var localOffset = lengthPosition - previousOffset;
  5393. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5394. }
  5395. previousOffset = nextOffset;
  5396. }
  5397. //Tools.Error("internal error");
  5398. return Vector2.Zero();
  5399. };
  5400. /**
  5401. * Returns a new Path2 starting at the coordinates (x, y).
  5402. */
  5403. Path2.StartingAt = function (x, y) {
  5404. return new Path2(x, y);
  5405. };
  5406. return Path2;
  5407. }());
  5408. BABYLON.Path2 = Path2;
  5409. var Path3D = /** @class */ (function () {
  5410. /**
  5411. * new Path3D(path, normal, raw)
  5412. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5413. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5414. * path : an array of Vector3, the curve axis of the Path3D
  5415. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5416. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5417. */
  5418. function Path3D(path, firstNormal, raw) {
  5419. if (firstNormal === void 0) { firstNormal = null; }
  5420. this.path = path;
  5421. this._curve = new Array();
  5422. this._distances = new Array();
  5423. this._tangents = new Array();
  5424. this._normals = new Array();
  5425. this._binormals = new Array();
  5426. for (var p = 0; p < path.length; p++) {
  5427. this._curve[p] = path[p].clone(); // hard copy
  5428. }
  5429. this._raw = raw || false;
  5430. this._compute(firstNormal);
  5431. }
  5432. /**
  5433. * Returns the Path3D array of successive Vector3 designing its curve.
  5434. */
  5435. Path3D.prototype.getCurve = function () {
  5436. return this._curve;
  5437. };
  5438. /**
  5439. * Returns an array populated with tangent vectors on each Path3D curve point.
  5440. */
  5441. Path3D.prototype.getTangents = function () {
  5442. return this._tangents;
  5443. };
  5444. /**
  5445. * Returns an array populated with normal vectors on each Path3D curve point.
  5446. */
  5447. Path3D.prototype.getNormals = function () {
  5448. return this._normals;
  5449. };
  5450. /**
  5451. * Returns an array populated with binormal vectors on each Path3D curve point.
  5452. */
  5453. Path3D.prototype.getBinormals = function () {
  5454. return this._binormals;
  5455. };
  5456. /**
  5457. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5458. */
  5459. Path3D.prototype.getDistances = function () {
  5460. return this._distances;
  5461. };
  5462. /**
  5463. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5464. * Returns the same object updated.
  5465. */
  5466. Path3D.prototype.update = function (path, firstNormal) {
  5467. if (firstNormal === void 0) { firstNormal = null; }
  5468. for (var p = 0; p < path.length; p++) {
  5469. this._curve[p].x = path[p].x;
  5470. this._curve[p].y = path[p].y;
  5471. this._curve[p].z = path[p].z;
  5472. }
  5473. this._compute(firstNormal);
  5474. return this;
  5475. };
  5476. // private function compute() : computes tangents, normals and binormals
  5477. Path3D.prototype._compute = function (firstNormal) {
  5478. var l = this._curve.length;
  5479. // first and last tangents
  5480. this._tangents[0] = this._getFirstNonNullVector(0);
  5481. if (!this._raw) {
  5482. this._tangents[0].normalize();
  5483. }
  5484. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5485. if (!this._raw) {
  5486. this._tangents[l - 1].normalize();
  5487. }
  5488. // normals and binormals at first point : arbitrary vector with _normalVector()
  5489. var tg0 = this._tangents[0];
  5490. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5491. this._normals[0] = pp0;
  5492. if (!this._raw) {
  5493. this._normals[0].normalize();
  5494. }
  5495. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5496. if (!this._raw) {
  5497. this._binormals[0].normalize();
  5498. }
  5499. this._distances[0] = 0.0;
  5500. // normals and binormals : next points
  5501. var prev; // previous vector (segment)
  5502. var cur; // current vector (segment)
  5503. var curTang; // current tangent
  5504. // previous normal
  5505. var prevBinor; // previous binormal
  5506. for (var i = 1; i < l; i++) {
  5507. // tangents
  5508. prev = this._getLastNonNullVector(i);
  5509. if (i < l - 1) {
  5510. cur = this._getFirstNonNullVector(i);
  5511. this._tangents[i] = prev.add(cur);
  5512. this._tangents[i].normalize();
  5513. }
  5514. this._distances[i] = this._distances[i - 1] + prev.length();
  5515. // normals and binormals
  5516. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5517. curTang = this._tangents[i];
  5518. prevBinor = this._binormals[i - 1];
  5519. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5520. if (!this._raw) {
  5521. this._normals[i].normalize();
  5522. }
  5523. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5524. if (!this._raw) {
  5525. this._binormals[i].normalize();
  5526. }
  5527. }
  5528. };
  5529. // private function getFirstNonNullVector(index)
  5530. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5531. Path3D.prototype._getFirstNonNullVector = function (index) {
  5532. var i = 1;
  5533. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5534. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5535. i++;
  5536. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5537. }
  5538. return nNVector;
  5539. };
  5540. // private function getLastNonNullVector(index)
  5541. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5542. Path3D.prototype._getLastNonNullVector = function (index) {
  5543. var i = 1;
  5544. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5545. while (nLVector.length() === 0 && index > i + 1) {
  5546. i++;
  5547. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5548. }
  5549. return nLVector;
  5550. };
  5551. // private function normalVector(v0, vt, va) :
  5552. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5553. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5554. Path3D.prototype._normalVector = function (v0, vt, va) {
  5555. var normal0;
  5556. var tgl = vt.length();
  5557. if (tgl === 0.0) {
  5558. tgl = 1.0;
  5559. }
  5560. if (va === undefined || va === null) {
  5561. var point;
  5562. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5563. point = new Vector3(0.0, -1.0, 0.0);
  5564. }
  5565. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5566. point = new Vector3(1.0, 0.0, 0.0);
  5567. }
  5568. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5569. point = new Vector3(0.0, 0.0, 1.0);
  5570. }
  5571. else {
  5572. point = Vector3.Zero();
  5573. }
  5574. normal0 = Vector3.Cross(vt, point);
  5575. }
  5576. else {
  5577. normal0 = Vector3.Cross(vt, va);
  5578. Vector3.CrossToRef(normal0, vt, normal0);
  5579. }
  5580. normal0.normalize();
  5581. return normal0;
  5582. };
  5583. return Path3D;
  5584. }());
  5585. BABYLON.Path3D = Path3D;
  5586. var Curve3 = /** @class */ (function () {
  5587. /**
  5588. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5589. * A Curve3 is designed from a series of successive Vector3.
  5590. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5591. */
  5592. function Curve3(points) {
  5593. this._length = 0.0;
  5594. this._points = points;
  5595. this._length = this._computeLength(points);
  5596. }
  5597. /**
  5598. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5599. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5600. * @param v1 (Vector3) the control point
  5601. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5602. * @param nbPoints (integer) the wanted number of points in the curve
  5603. */
  5604. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5605. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5606. var bez = new Array();
  5607. var equation = function (t, val0, val1, val2) {
  5608. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5609. return res;
  5610. };
  5611. for (var i = 0; i <= nbPoints; i++) {
  5612. 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)));
  5613. }
  5614. return new Curve3(bez);
  5615. };
  5616. /**
  5617. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5618. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5619. * @param v1 (Vector3) the first control point
  5620. * @param v2 (Vector3) the second control point
  5621. * @param v3 (Vector3) the end point of the Cubic Bezier
  5622. * @param nbPoints (integer) the wanted number of points in the curve
  5623. */
  5624. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5625. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5626. var bez = new Array();
  5627. var equation = function (t, val0, val1, val2, val3) {
  5628. 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;
  5629. return res;
  5630. };
  5631. for (var i = 0; i <= nbPoints; i++) {
  5632. 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)));
  5633. }
  5634. return new Curve3(bez);
  5635. };
  5636. /**
  5637. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5638. * @param p1 (Vector3) the origin point of the Hermite Spline
  5639. * @param t1 (Vector3) the tangent vector at the origin point
  5640. * @param p2 (Vector3) the end point of the Hermite Spline
  5641. * @param t2 (Vector3) the tangent vector at the end point
  5642. * @param nbPoints (integer) the wanted number of points in the curve
  5643. */
  5644. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5645. var hermite = new Array();
  5646. var step = 1.0 / nbPoints;
  5647. for (var i = 0; i <= nbPoints; i++) {
  5648. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5649. }
  5650. return new Curve3(hermite);
  5651. };
  5652. /**
  5653. * Returns a Curve3 object along a CatmullRom Spline curve :
  5654. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5655. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5656. */
  5657. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5658. var totalPoints = new Array();
  5659. totalPoints.push(points[0].clone());
  5660. Array.prototype.push.apply(totalPoints, points);
  5661. totalPoints.push(points[points.length - 1].clone());
  5662. var catmullRom = new Array();
  5663. var step = 1.0 / nbPoints;
  5664. var amount = 0.0;
  5665. for (var i = 0; i < totalPoints.length - 3; i++) {
  5666. amount = 0;
  5667. for (var c = 0; c < nbPoints; c++) {
  5668. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5669. amount += step;
  5670. }
  5671. }
  5672. i--;
  5673. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5674. return new Curve3(catmullRom);
  5675. };
  5676. /**
  5677. * Returns the Curve3 stored array of successive Vector3
  5678. */
  5679. Curve3.prototype.getPoints = function () {
  5680. return this._points;
  5681. };
  5682. /**
  5683. * Returns the computed length (float) of the curve.
  5684. */
  5685. Curve3.prototype.length = function () {
  5686. return this._length;
  5687. };
  5688. /**
  5689. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5690. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5691. * curveA and curveB keep unchanged.
  5692. */
  5693. Curve3.prototype.continue = function (curve) {
  5694. var lastPoint = this._points[this._points.length - 1];
  5695. var continuedPoints = this._points.slice();
  5696. var curvePoints = curve.getPoints();
  5697. for (var i = 1; i < curvePoints.length; i++) {
  5698. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5699. }
  5700. var continuedCurve = new Curve3(continuedPoints);
  5701. return continuedCurve;
  5702. };
  5703. Curve3.prototype._computeLength = function (path) {
  5704. var l = 0;
  5705. for (var i = 1; i < path.length; i++) {
  5706. l += (path[i].subtract(path[i - 1])).length();
  5707. }
  5708. return l;
  5709. };
  5710. return Curve3;
  5711. }());
  5712. BABYLON.Curve3 = Curve3;
  5713. // Vertex formats
  5714. var PositionNormalVertex = /** @class */ (function () {
  5715. function PositionNormalVertex(position, normal) {
  5716. if (position === void 0) { position = Vector3.Zero(); }
  5717. if (normal === void 0) { normal = Vector3.Up(); }
  5718. this.position = position;
  5719. this.normal = normal;
  5720. }
  5721. PositionNormalVertex.prototype.clone = function () {
  5722. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5723. };
  5724. return PositionNormalVertex;
  5725. }());
  5726. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5727. var PositionNormalTextureVertex = /** @class */ (function () {
  5728. function PositionNormalTextureVertex(position, normal, uv) {
  5729. if (position === void 0) { position = Vector3.Zero(); }
  5730. if (normal === void 0) { normal = Vector3.Up(); }
  5731. if (uv === void 0) { uv = Vector2.Zero(); }
  5732. this.position = position;
  5733. this.normal = normal;
  5734. this.uv = uv;
  5735. }
  5736. PositionNormalTextureVertex.prototype.clone = function () {
  5737. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5738. };
  5739. return PositionNormalTextureVertex;
  5740. }());
  5741. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5742. // Temporary pre-allocated objects for engine internal use
  5743. // usage in any internal function :
  5744. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5745. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5746. var Tmp = /** @class */ (function () {
  5747. function Tmp() {
  5748. }
  5749. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5750. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5751. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5752. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5753. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5754. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5755. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5756. Matrix.Zero(), Matrix.Zero(),
  5757. Matrix.Zero(), Matrix.Zero(),
  5758. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5759. return Tmp;
  5760. }());
  5761. BABYLON.Tmp = Tmp;
  5762. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5763. var MathTmp = /** @class */ (function () {
  5764. function MathTmp() {
  5765. }
  5766. MathTmp.Vector3 = [Vector3.Zero()];
  5767. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5768. MathTmp.Quaternion = [Quaternion.Zero()];
  5769. return MathTmp;
  5770. }());
  5771. })(BABYLON || (BABYLON = {}));
  5772. //# sourceMappingURL=babylon.math.js.map
  5773. var BABYLON;
  5774. (function (BABYLON) {
  5775. var Scalar = /** @class */ (function () {
  5776. function Scalar() {
  5777. }
  5778. /**
  5779. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5780. */
  5781. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5782. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5783. var num = a - b;
  5784. return -epsilon <= num && num <= epsilon;
  5785. };
  5786. /**
  5787. * Returns a string : the upper case translation of the number i to hexadecimal.
  5788. */
  5789. Scalar.ToHex = function (i) {
  5790. var str = i.toString(16);
  5791. if (i <= 15) {
  5792. return ("0" + str).toUpperCase();
  5793. }
  5794. return str.toUpperCase();
  5795. };
  5796. /**
  5797. * Returns -1 if value is negative and +1 is value is positive.
  5798. * Returns the value itself if it's equal to zero.
  5799. */
  5800. Scalar.Sign = function (value) {
  5801. value = +value; // convert to a number
  5802. if (value === 0 || isNaN(value))
  5803. return value;
  5804. return value > 0 ? 1 : -1;
  5805. };
  5806. /**
  5807. * Returns the value itself if it's between min and max.
  5808. * Returns min if the value is lower than min.
  5809. * Returns max if the value is greater than max.
  5810. */
  5811. Scalar.Clamp = function (value, min, max) {
  5812. if (min === void 0) { min = 0; }
  5813. if (max === void 0) { max = 1; }
  5814. return Math.min(max, Math.max(min, value));
  5815. };
  5816. /**
  5817. * Returns the log2 of value.
  5818. */
  5819. Scalar.Log2 = function (value) {
  5820. return Math.log(value) * Math.LOG2E;
  5821. };
  5822. /**
  5823. * Loops the value, so that it is never larger than length and never smaller than 0.
  5824. *
  5825. * This is similar to the modulo operator but it works with floating point numbers.
  5826. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5827. * With t = 5 and length = 2.5, the result would be 0.0.
  5828. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5829. */
  5830. Scalar.Repeat = function (value, length) {
  5831. return value - Math.floor(value / length) * length;
  5832. };
  5833. /**
  5834. * Normalize the value between 0.0 and 1.0 using min and max values
  5835. */
  5836. Scalar.Normalize = function (value, min, max) {
  5837. return (value - min) / (max - min);
  5838. };
  5839. /**
  5840. * Denormalize the value from 0.0 and 1.0 using min and max values
  5841. */
  5842. Scalar.Denormalize = function (normalized, min, max) {
  5843. return (normalized * (max - min) + min);
  5844. };
  5845. /**
  5846. * Calculates the shortest difference between two given angles given in degrees.
  5847. */
  5848. Scalar.DeltaAngle = function (current, target) {
  5849. var num = Scalar.Repeat(target - current, 360.0);
  5850. if (num > 180.0) {
  5851. num -= 360.0;
  5852. }
  5853. return num;
  5854. };
  5855. /**
  5856. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5857. *
  5858. * The returned value will move back and forth between 0 and length
  5859. */
  5860. Scalar.PingPong = function (tx, length) {
  5861. var t = Scalar.Repeat(tx, length * 2.0);
  5862. return length - Math.abs(t - length);
  5863. };
  5864. /**
  5865. * Interpolates between min and max with smoothing at the limits.
  5866. *
  5867. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5868. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5869. */
  5870. Scalar.SmoothStep = function (from, to, tx) {
  5871. var t = Scalar.Clamp(tx);
  5872. t = -2.0 * t * t * t + 3.0 * t * t;
  5873. return to * t + from * (1.0 - t);
  5874. };
  5875. /**
  5876. * Moves a value current towards target.
  5877. *
  5878. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5879. * Negative values of maxDelta pushes the value away from target.
  5880. */
  5881. Scalar.MoveTowards = function (current, target, maxDelta) {
  5882. var result = 0;
  5883. if (Math.abs(target - current) <= maxDelta) {
  5884. result = target;
  5885. }
  5886. else {
  5887. result = current + Scalar.Sign(target - current) * maxDelta;
  5888. }
  5889. return result;
  5890. };
  5891. /**
  5892. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5893. *
  5894. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5895. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5896. */
  5897. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5898. var num = Scalar.DeltaAngle(current, target);
  5899. var result = 0;
  5900. if (-maxDelta < num && num < maxDelta) {
  5901. result = target;
  5902. }
  5903. else {
  5904. target = current + num;
  5905. result = Scalar.MoveTowards(current, target, maxDelta);
  5906. }
  5907. return result;
  5908. };
  5909. /**
  5910. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5911. */
  5912. Scalar.Lerp = function (start, end, amount) {
  5913. return start + ((end - start) * amount);
  5914. };
  5915. /**
  5916. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5917. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5918. */
  5919. Scalar.LerpAngle = function (start, end, amount) {
  5920. var num = Scalar.Repeat(end - start, 360.0);
  5921. if (num > 180.0) {
  5922. num -= 360.0;
  5923. }
  5924. return start + num * Scalar.Clamp(amount);
  5925. };
  5926. /**
  5927. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5928. */
  5929. Scalar.InverseLerp = function (a, b, value) {
  5930. var result = 0;
  5931. if (a != b) {
  5932. result = Scalar.Clamp((value - a) / (b - a));
  5933. }
  5934. else {
  5935. result = 0.0;
  5936. }
  5937. return result;
  5938. };
  5939. /**
  5940. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5941. */
  5942. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5943. var squared = amount * amount;
  5944. var cubed = amount * squared;
  5945. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5946. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5947. var part3 = (cubed - (2.0 * squared)) + amount;
  5948. var part4 = cubed - squared;
  5949. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5950. };
  5951. /**
  5952. * Returns a random float number between and min and max values
  5953. */
  5954. Scalar.RandomRange = function (min, max) {
  5955. if (min === max)
  5956. return min;
  5957. return ((Math.random() * (max - min)) + min);
  5958. };
  5959. /**
  5960. * This function returns percentage of a number in a given range.
  5961. *
  5962. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5963. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5964. */
  5965. Scalar.RangeToPercent = function (number, min, max) {
  5966. return ((number - min) / (max - min));
  5967. };
  5968. /**
  5969. * This function returns number that corresponds to the percentage in a given range.
  5970. *
  5971. * PercentToRange(0.34,0,100) will return 34.
  5972. */
  5973. Scalar.PercentToRange = function (percent, min, max) {
  5974. return ((max - min) * percent + min);
  5975. };
  5976. /**
  5977. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5978. * @param angle The angle to normalize in radian.
  5979. * @return The converted angle.
  5980. */
  5981. Scalar.NormalizeRadians = function (angle) {
  5982. // More precise but slower version kept for reference.
  5983. // angle = angle % Tools.TwoPi;
  5984. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5985. //if (angle > Math.PI) {
  5986. // angle -= Tools.TwoPi;
  5987. //}
  5988. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5989. return angle;
  5990. };
  5991. /**
  5992. * Two pi constants convenient for computation.
  5993. */
  5994. Scalar.TwoPi = Math.PI * 2;
  5995. return Scalar;
  5996. }());
  5997. BABYLON.Scalar = Scalar;
  5998. })(BABYLON || (BABYLON = {}));
  5999. //# sourceMappingURL=babylon.math.scalar.js.map
  6000. //# sourceMappingURL=babylon.mixins.js.map
  6001. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6002. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6003. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6004. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6005. //# sourceMappingURL=babylon.webgl2.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var __decoratorInitialStore = {};
  6009. var __mergedStore = {};
  6010. var _copySource = function (creationFunction, source, instanciate) {
  6011. var destination = creationFunction();
  6012. // Tags
  6013. if (BABYLON.Tags) {
  6014. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6015. }
  6016. var classStore = getMergedStore(destination);
  6017. // Properties
  6018. for (var property in classStore) {
  6019. var propertyDescriptor = classStore[property];
  6020. var sourceProperty = source[property];
  6021. var propertyType = propertyDescriptor.type;
  6022. if (sourceProperty !== undefined && sourceProperty !== null) {
  6023. switch (propertyType) {
  6024. case 0: // Value
  6025. case 6:// Mesh reference
  6026. destination[property] = sourceProperty;
  6027. break;
  6028. case 1:// Texture
  6029. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6030. break;
  6031. case 2: // Color3
  6032. case 3: // FresnelParameters
  6033. case 4: // Vector2
  6034. case 5: // Vector3
  6035. case 7: // Color Curves
  6036. case 10:// Quaternion
  6037. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6038. break;
  6039. }
  6040. }
  6041. }
  6042. return destination;
  6043. };
  6044. function getDirectStore(target) {
  6045. var classKey = target.getClassName();
  6046. if (!__decoratorInitialStore[classKey]) {
  6047. __decoratorInitialStore[classKey] = {};
  6048. }
  6049. return __decoratorInitialStore[classKey];
  6050. }
  6051. /**
  6052. * Return the list of properties flagged as serializable
  6053. * @param target: host object
  6054. */
  6055. function getMergedStore(target) {
  6056. var classKey = target.getClassName();
  6057. if (__mergedStore[classKey]) {
  6058. return __mergedStore[classKey];
  6059. }
  6060. __mergedStore[classKey] = {};
  6061. var store = __mergedStore[classKey];
  6062. var currentTarget = target;
  6063. var currentKey = classKey;
  6064. while (currentKey) {
  6065. var initialStore = __decoratorInitialStore[currentKey];
  6066. for (var property in initialStore) {
  6067. store[property] = initialStore[property];
  6068. }
  6069. var parent_1 = void 0;
  6070. var done = false;
  6071. do {
  6072. parent_1 = Object.getPrototypeOf(currentTarget);
  6073. if (!parent_1.getClassName) {
  6074. done = true;
  6075. break;
  6076. }
  6077. if (parent_1.getClassName() !== currentKey) {
  6078. break;
  6079. }
  6080. currentTarget = parent_1;
  6081. } while (parent_1);
  6082. if (done) {
  6083. break;
  6084. }
  6085. currentKey = parent_1.getClassName();
  6086. currentTarget = parent_1;
  6087. }
  6088. return store;
  6089. }
  6090. function generateSerializableMember(type, sourceName) {
  6091. return function (target, propertyKey) {
  6092. var classStore = getDirectStore(target);
  6093. if (!classStore[propertyKey]) {
  6094. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6095. }
  6096. };
  6097. }
  6098. function generateExpandMember(setCallback, targetKey) {
  6099. if (targetKey === void 0) { targetKey = null; }
  6100. return function (target, propertyKey) {
  6101. var key = targetKey || ("_" + propertyKey);
  6102. Object.defineProperty(target, propertyKey, {
  6103. get: function () {
  6104. return this[key];
  6105. },
  6106. set: function (value) {
  6107. if (this[key] === value) {
  6108. return;
  6109. }
  6110. this[key] = value;
  6111. target[setCallback].apply(this);
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. };
  6117. }
  6118. function expandToProperty(callback, targetKey) {
  6119. if (targetKey === void 0) { targetKey = null; }
  6120. return generateExpandMember(callback, targetKey);
  6121. }
  6122. BABYLON.expandToProperty = expandToProperty;
  6123. function serialize(sourceName) {
  6124. return generateSerializableMember(0, sourceName); // value member
  6125. }
  6126. BABYLON.serialize = serialize;
  6127. function serializeAsTexture(sourceName) {
  6128. return generateSerializableMember(1, sourceName); // texture member
  6129. }
  6130. BABYLON.serializeAsTexture = serializeAsTexture;
  6131. function serializeAsColor3(sourceName) {
  6132. return generateSerializableMember(2, sourceName); // color3 member
  6133. }
  6134. BABYLON.serializeAsColor3 = serializeAsColor3;
  6135. function serializeAsFresnelParameters(sourceName) {
  6136. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6137. }
  6138. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6139. function serializeAsVector2(sourceName) {
  6140. return generateSerializableMember(4, sourceName); // vector2 member
  6141. }
  6142. BABYLON.serializeAsVector2 = serializeAsVector2;
  6143. function serializeAsVector3(sourceName) {
  6144. return generateSerializableMember(5, sourceName); // vector3 member
  6145. }
  6146. BABYLON.serializeAsVector3 = serializeAsVector3;
  6147. function serializeAsMeshReference(sourceName) {
  6148. return generateSerializableMember(6, sourceName); // mesh reference member
  6149. }
  6150. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6151. function serializeAsColorCurves(sourceName) {
  6152. return generateSerializableMember(7, sourceName); // color curves
  6153. }
  6154. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6155. function serializeAsColor4(sourceName) {
  6156. return generateSerializableMember(8, sourceName); // color 4
  6157. }
  6158. BABYLON.serializeAsColor4 = serializeAsColor4;
  6159. function serializeAsImageProcessingConfiguration(sourceName) {
  6160. return generateSerializableMember(9, sourceName); // image processing
  6161. }
  6162. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6163. function serializeAsQuaternion(sourceName) {
  6164. return generateSerializableMember(10, sourceName); // quaternion member
  6165. }
  6166. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6167. var SerializationHelper = /** @class */ (function () {
  6168. function SerializationHelper() {
  6169. }
  6170. SerializationHelper.Serialize = function (entity, serializationObject) {
  6171. if (!serializationObject) {
  6172. serializationObject = {};
  6173. }
  6174. // Tags
  6175. if (BABYLON.Tags) {
  6176. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6177. }
  6178. var serializedProperties = getMergedStore(entity);
  6179. // Properties
  6180. for (var property in serializedProperties) {
  6181. var propertyDescriptor = serializedProperties[property];
  6182. var targetPropertyName = propertyDescriptor.sourceName || property;
  6183. var propertyType = propertyDescriptor.type;
  6184. var sourceProperty = entity[property];
  6185. if (sourceProperty !== undefined && sourceProperty !== null) {
  6186. switch (propertyType) {
  6187. case 0:// Value
  6188. serializationObject[targetPropertyName] = sourceProperty;
  6189. break;
  6190. case 1:// Texture
  6191. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6192. break;
  6193. case 2:// Color3
  6194. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6195. break;
  6196. case 3:// FresnelParameters
  6197. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6198. break;
  6199. case 4:// Vector2
  6200. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6201. break;
  6202. case 5:// Vector3
  6203. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6204. break;
  6205. case 6:// Mesh reference
  6206. serializationObject[targetPropertyName] = sourceProperty.id;
  6207. break;
  6208. case 7:// Color Curves
  6209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6210. break;
  6211. case 8:// Color 4
  6212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6213. break;
  6214. case 9:// Image Processing
  6215. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6216. break;
  6217. }
  6218. }
  6219. }
  6220. return serializationObject;
  6221. };
  6222. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6223. if (rootUrl === void 0) { rootUrl = null; }
  6224. var destination = creationFunction();
  6225. if (!rootUrl) {
  6226. rootUrl = "";
  6227. }
  6228. // Tags
  6229. if (BABYLON.Tags) {
  6230. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6231. }
  6232. var classStore = getMergedStore(destination);
  6233. // Properties
  6234. for (var property in classStore) {
  6235. var propertyDescriptor = classStore[property];
  6236. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6237. var propertyType = propertyDescriptor.type;
  6238. if (sourceProperty !== undefined && sourceProperty !== null) {
  6239. var dest = destination;
  6240. switch (propertyType) {
  6241. case 0:// Value
  6242. dest[property] = sourceProperty;
  6243. break;
  6244. case 1:// Texture
  6245. if (scene) {
  6246. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6247. }
  6248. break;
  6249. case 2:// Color3
  6250. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6251. break;
  6252. case 3:// FresnelParameters
  6253. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6254. break;
  6255. case 4:// Vector2
  6256. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6257. break;
  6258. case 5:// Vector3
  6259. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6260. break;
  6261. case 6:// Mesh reference
  6262. if (scene) {
  6263. dest[property] = scene.getLastMeshByID(sourceProperty);
  6264. }
  6265. break;
  6266. case 7:// Color Curves
  6267. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6268. break;
  6269. case 8:// Color 4
  6270. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6271. break;
  6272. case 9:// Image Processing
  6273. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6274. break;
  6275. }
  6276. }
  6277. }
  6278. return destination;
  6279. };
  6280. SerializationHelper.Clone = function (creationFunction, source) {
  6281. return _copySource(creationFunction, source, false);
  6282. };
  6283. SerializationHelper.Instanciate = function (creationFunction, source) {
  6284. return _copySource(creationFunction, source, true);
  6285. };
  6286. return SerializationHelper;
  6287. }());
  6288. BABYLON.SerializationHelper = SerializationHelper;
  6289. })(BABYLON || (BABYLON = {}));
  6290. //# sourceMappingURL=babylon.decorators.js.map
  6291. var BABYLON;
  6292. (function (BABYLON) {
  6293. /**
  6294. * A class serves as a medium between the observable and its observers
  6295. */
  6296. var EventState = /** @class */ (function () {
  6297. /**
  6298. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6299. */
  6300. function EventState(mask, skipNextObservers, target, currentTarget) {
  6301. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6302. this.initalize(mask, skipNextObservers, target, currentTarget);
  6303. }
  6304. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6305. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6306. this.mask = mask;
  6307. this.skipNextObservers = skipNextObservers;
  6308. this.target = target;
  6309. this.currentTarget = currentTarget;
  6310. return this;
  6311. };
  6312. return EventState;
  6313. }());
  6314. BABYLON.EventState = EventState;
  6315. /**
  6316. * Represent an Observer registered to a given Observable object.
  6317. */
  6318. var Observer = /** @class */ (function () {
  6319. function Observer(callback, mask, scope) {
  6320. if (scope === void 0) { scope = null; }
  6321. this.callback = callback;
  6322. this.mask = mask;
  6323. this.scope = scope;
  6324. }
  6325. return Observer;
  6326. }());
  6327. BABYLON.Observer = Observer;
  6328. /**
  6329. * Represent a list of observers registered to multiple Observables object.
  6330. */
  6331. var MultiObserver = /** @class */ (function () {
  6332. function MultiObserver() {
  6333. }
  6334. MultiObserver.prototype.dispose = function () {
  6335. if (this._observers && this._observables) {
  6336. for (var index = 0; index < this._observers.length; index++) {
  6337. this._observables[index].remove(this._observers[index]);
  6338. }
  6339. }
  6340. this._observers = null;
  6341. this._observables = null;
  6342. };
  6343. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6344. if (mask === void 0) { mask = -1; }
  6345. if (scope === void 0) { scope = null; }
  6346. var result = new MultiObserver();
  6347. result._observers = new Array();
  6348. result._observables = observables;
  6349. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6350. var observable = observables_1[_i];
  6351. var observer = observable.add(callback, mask, false, scope);
  6352. if (observer) {
  6353. result._observers.push(observer);
  6354. }
  6355. }
  6356. return result;
  6357. };
  6358. return MultiObserver;
  6359. }());
  6360. BABYLON.MultiObserver = MultiObserver;
  6361. /**
  6362. * The Observable class is a simple implementation of the Observable pattern.
  6363. * 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.
  6364. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6365. * 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).
  6366. * 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.
  6367. */
  6368. var Observable = /** @class */ (function () {
  6369. function Observable(onObserverAdded) {
  6370. this._observers = new Array();
  6371. this._eventState = new EventState(0);
  6372. if (onObserverAdded) {
  6373. this._onObserverAdded = onObserverAdded;
  6374. }
  6375. }
  6376. /**
  6377. * Create a new Observer with the specified callback
  6378. * @param callback the callback that will be executed for that Observer
  6379. * @param mask the mask used to filter observers
  6380. * @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.
  6381. * @param scope optional scope for the callback to be called from
  6382. */
  6383. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6384. if (mask === void 0) { mask = -1; }
  6385. if (insertFirst === void 0) { insertFirst = false; }
  6386. if (scope === void 0) { scope = null; }
  6387. if (!callback) {
  6388. return null;
  6389. }
  6390. var observer = new Observer(callback, mask, scope);
  6391. if (insertFirst) {
  6392. this._observers.unshift(observer);
  6393. }
  6394. else {
  6395. this._observers.push(observer);
  6396. }
  6397. if (this._onObserverAdded) {
  6398. this._onObserverAdded(observer);
  6399. }
  6400. return observer;
  6401. };
  6402. /**
  6403. * Remove an Observer from the Observable object
  6404. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6405. */
  6406. Observable.prototype.remove = function (observer) {
  6407. if (!observer) {
  6408. return false;
  6409. }
  6410. var index = this._observers.indexOf(observer);
  6411. if (index !== -1) {
  6412. this._observers.splice(index, 1);
  6413. return true;
  6414. }
  6415. return false;
  6416. };
  6417. /**
  6418. * Remove a callback from the Observable object
  6419. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6420. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6421. */
  6422. Observable.prototype.removeCallback = function (callback, scope) {
  6423. for (var index = 0; index < this._observers.length; index++) {
  6424. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6425. this._observers.splice(index, 1);
  6426. return true;
  6427. }
  6428. }
  6429. return false;
  6430. };
  6431. /**
  6432. * Notify all Observers by calling their respective callback with the given data
  6433. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6434. * @param eventData
  6435. * @param mask
  6436. */
  6437. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6438. if (mask === void 0) { mask = -1; }
  6439. if (!this._observers.length) {
  6440. return true;
  6441. }
  6442. var state = this._eventState;
  6443. state.mask = mask;
  6444. state.target = target;
  6445. state.currentTarget = currentTarget;
  6446. state.skipNextObservers = false;
  6447. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6448. var obs = _a[_i];
  6449. if (obs.mask & mask) {
  6450. if (obs.scope) {
  6451. obs.callback.apply(obs.scope, [eventData, state]);
  6452. }
  6453. else {
  6454. obs.callback(eventData, state);
  6455. }
  6456. }
  6457. if (state.skipNextObservers) {
  6458. return false;
  6459. }
  6460. }
  6461. return true;
  6462. };
  6463. /**
  6464. * Notify a specific observer
  6465. * @param eventData
  6466. * @param mask
  6467. */
  6468. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6469. if (mask === void 0) { mask = -1; }
  6470. var state = this._eventState;
  6471. state.mask = mask;
  6472. state.skipNextObservers = false;
  6473. observer.callback(eventData, state);
  6474. };
  6475. /**
  6476. * return true is the Observable has at least one Observer registered
  6477. */
  6478. Observable.prototype.hasObservers = function () {
  6479. return this._observers.length > 0;
  6480. };
  6481. /**
  6482. * Clear the list of observers
  6483. */
  6484. Observable.prototype.clear = function () {
  6485. this._observers = new Array();
  6486. this._onObserverAdded = null;
  6487. };
  6488. /**
  6489. * Clone the current observable
  6490. */
  6491. Observable.prototype.clone = function () {
  6492. var result = new Observable();
  6493. result._observers = this._observers.slice(0);
  6494. return result;
  6495. };
  6496. /**
  6497. * Does this observable handles observer registered with a given mask
  6498. * @param {number} trigger - the mask to be tested
  6499. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6500. **/
  6501. Observable.prototype.hasSpecificMask = function (mask) {
  6502. if (mask === void 0) { mask = -1; }
  6503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6504. var obs = _a[_i];
  6505. if (obs.mask & mask || obs.mask === mask) {
  6506. return true;
  6507. }
  6508. }
  6509. return false;
  6510. };
  6511. return Observable;
  6512. }());
  6513. BABYLON.Observable = Observable;
  6514. })(BABYLON || (BABYLON = {}));
  6515. //# sourceMappingURL=babylon.observable.js.map
  6516. var BABYLON;
  6517. (function (BABYLON) {
  6518. var SmartArray = /** @class */ (function () {
  6519. function SmartArray(capacity) {
  6520. this.length = 0;
  6521. this.data = new Array(capacity);
  6522. this._id = SmartArray._GlobalId++;
  6523. }
  6524. SmartArray.prototype.push = function (value) {
  6525. this.data[this.length++] = value;
  6526. if (this.length > this.data.length) {
  6527. this.data.length *= 2;
  6528. }
  6529. };
  6530. SmartArray.prototype.forEach = function (func) {
  6531. for (var index = 0; index < this.length; index++) {
  6532. func(this.data[index]);
  6533. }
  6534. };
  6535. SmartArray.prototype.sort = function (compareFn) {
  6536. this.data.sort(compareFn);
  6537. };
  6538. SmartArray.prototype.reset = function () {
  6539. this.length = 0;
  6540. };
  6541. SmartArray.prototype.dispose = function () {
  6542. this.reset();
  6543. if (this.data) {
  6544. this.data.length = 0;
  6545. this.data = [];
  6546. }
  6547. };
  6548. SmartArray.prototype.concat = function (array) {
  6549. if (array.length === 0) {
  6550. return;
  6551. }
  6552. if (this.length + array.length > this.data.length) {
  6553. this.data.length = (this.length + array.length) * 2;
  6554. }
  6555. for (var index = 0; index < array.length; index++) {
  6556. this.data[this.length++] = (array.data || array)[index];
  6557. }
  6558. };
  6559. SmartArray.prototype.indexOf = function (value) {
  6560. var position = this.data.indexOf(value);
  6561. if (position >= this.length) {
  6562. return -1;
  6563. }
  6564. return position;
  6565. };
  6566. SmartArray.prototype.contains = function (value) {
  6567. return this.data.indexOf(value) !== -1;
  6568. };
  6569. // Statics
  6570. SmartArray._GlobalId = 0;
  6571. return SmartArray;
  6572. }());
  6573. BABYLON.SmartArray = SmartArray;
  6574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6575. __extends(SmartArrayNoDuplicate, _super);
  6576. function SmartArrayNoDuplicate() {
  6577. var _this = _super !== null && _super.apply(this, arguments) || this;
  6578. _this._duplicateId = 0;
  6579. return _this;
  6580. }
  6581. SmartArrayNoDuplicate.prototype.push = function (value) {
  6582. _super.prototype.push.call(this, value);
  6583. if (!value.__smartArrayFlags) {
  6584. value.__smartArrayFlags = {};
  6585. }
  6586. value.__smartArrayFlags[this._id] = this._duplicateId;
  6587. };
  6588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6590. return false;
  6591. }
  6592. this.push(value);
  6593. return true;
  6594. };
  6595. SmartArrayNoDuplicate.prototype.reset = function () {
  6596. _super.prototype.reset.call(this);
  6597. this._duplicateId++;
  6598. };
  6599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6600. if (array.length === 0) {
  6601. return;
  6602. }
  6603. if (this.length + array.length > this.data.length) {
  6604. this.data.length = (this.length + array.length) * 2;
  6605. }
  6606. for (var index = 0; index < array.length; index++) {
  6607. var item = (array.data || array)[index];
  6608. this.pushNoDuplicate(item);
  6609. }
  6610. };
  6611. return SmartArrayNoDuplicate;
  6612. }(SmartArray));
  6613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6614. })(BABYLON || (BABYLON = {}));
  6615. //# sourceMappingURL=babylon.smartArray.js.map
  6616. var BABYLON;
  6617. (function (BABYLON) {
  6618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6620. var LoadFileError = /** @class */ (function (_super) {
  6621. __extends(LoadFileError, _super);
  6622. function LoadFileError(message, request) {
  6623. var _this = _super.call(this, message) || this;
  6624. _this.request = request;
  6625. _this.name = "LoadFileError";
  6626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6627. return _this;
  6628. }
  6629. // Polyfill for Object.setPrototypeOf if necessary.
  6630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6631. return LoadFileError;
  6632. }(Error));
  6633. BABYLON.LoadFileError = LoadFileError;
  6634. var RetryStrategy = /** @class */ (function () {
  6635. function RetryStrategy() {
  6636. }
  6637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6638. if (maxRetries === void 0) { maxRetries = 3; }
  6639. if (baseInterval === void 0) { baseInterval = 500; }
  6640. return function (url, request, retryIndex) {
  6641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6642. return -1;
  6643. }
  6644. return Math.pow(2, retryIndex) * baseInterval;
  6645. };
  6646. };
  6647. return RetryStrategy;
  6648. }());
  6649. BABYLON.RetryStrategy = RetryStrategy;
  6650. // Screenshots
  6651. var screenshotCanvas;
  6652. var cloneValue = function (source, destinationObject) {
  6653. if (!source)
  6654. return null;
  6655. if (source instanceof BABYLON.Mesh) {
  6656. return null;
  6657. }
  6658. if (source instanceof BABYLON.SubMesh) {
  6659. return source.clone(destinationObject);
  6660. }
  6661. else if (source.clone) {
  6662. return source.clone();
  6663. }
  6664. return null;
  6665. };
  6666. var Tools = /** @class */ (function () {
  6667. function Tools() {
  6668. }
  6669. /**
  6670. * Interpolates between a and b via alpha
  6671. * @param a The lower value (returned when alpha = 0)
  6672. * @param b The upper value (returned when alpha = 1)
  6673. * @param alpha The interpolation-factor
  6674. * @return The mixed value
  6675. */
  6676. Tools.Mix = function (a, b, alpha) {
  6677. return a * (1 - alpha) + b * alpha;
  6678. };
  6679. Tools.Instantiate = function (className) {
  6680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6681. return Tools.RegisteredExternalClasses[className];
  6682. }
  6683. var arr = className.split(".");
  6684. var fn = (window || this);
  6685. for (var i = 0, len = arr.length; i < len; i++) {
  6686. fn = fn[arr[i]];
  6687. }
  6688. if (typeof fn !== "function") {
  6689. return null;
  6690. }
  6691. return fn;
  6692. };
  6693. Tools.SetImmediate = function (action) {
  6694. if (window.setImmediate) {
  6695. window.setImmediate(action);
  6696. }
  6697. else {
  6698. setTimeout(action, 1);
  6699. }
  6700. };
  6701. Tools.IsExponentOfTwo = function (value) {
  6702. var count = 1;
  6703. do {
  6704. count *= 2;
  6705. } while (count < value);
  6706. return count === value;
  6707. };
  6708. /**
  6709. * Find the next highest power of two.
  6710. * @param x Number to start search from.
  6711. * @return Next highest power of two.
  6712. */
  6713. Tools.CeilingPOT = function (x) {
  6714. x--;
  6715. x |= x >> 1;
  6716. x |= x >> 2;
  6717. x |= x >> 4;
  6718. x |= x >> 8;
  6719. x |= x >> 16;
  6720. x++;
  6721. return x;
  6722. };
  6723. /**
  6724. * Find the next lowest power of two.
  6725. * @param x Number to start search from.
  6726. * @return Next lowest power of two.
  6727. */
  6728. Tools.FloorPOT = function (x) {
  6729. x = x | (x >> 1);
  6730. x = x | (x >> 2);
  6731. x = x | (x >> 4);
  6732. x = x | (x >> 8);
  6733. x = x | (x >> 16);
  6734. return x - (x >> 1);
  6735. };
  6736. /**
  6737. * Find the nearest power of two.
  6738. * @param x Number to start search from.
  6739. * @return Next nearest power of two.
  6740. */
  6741. Tools.NearestPOT = function (x) {
  6742. var c = Tools.CeilingPOT(x);
  6743. var f = Tools.FloorPOT(x);
  6744. return (c - x) > (x - f) ? f : c;
  6745. };
  6746. Tools.GetExponentOfTwo = function (value, max, mode) {
  6747. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6748. var pot;
  6749. switch (mode) {
  6750. case BABYLON.Engine.SCALEMODE_FLOOR:
  6751. pot = Tools.FloorPOT(value);
  6752. break;
  6753. case BABYLON.Engine.SCALEMODE_NEAREST:
  6754. pot = Tools.NearestPOT(value);
  6755. break;
  6756. case BABYLON.Engine.SCALEMODE_CEILING:
  6757. default:
  6758. pot = Tools.CeilingPOT(value);
  6759. break;
  6760. }
  6761. return Math.min(pot, max);
  6762. };
  6763. Tools.GetFilename = function (path) {
  6764. var index = path.lastIndexOf("/");
  6765. if (index < 0)
  6766. return path;
  6767. return path.substring(index + 1);
  6768. };
  6769. Tools.GetFolderPath = function (uri) {
  6770. var index = uri.lastIndexOf("/");
  6771. if (index < 0)
  6772. return "";
  6773. return uri.substring(0, index + 1);
  6774. };
  6775. Tools.GetDOMTextContent = function (element) {
  6776. var result = "";
  6777. var child = element.firstChild;
  6778. while (child) {
  6779. if (child.nodeType === 3) {
  6780. result += child.textContent;
  6781. }
  6782. child = child.nextSibling;
  6783. }
  6784. return result;
  6785. };
  6786. Tools.ToDegrees = function (angle) {
  6787. return angle * 180 / Math.PI;
  6788. };
  6789. Tools.ToRadians = function (angle) {
  6790. return angle * Math.PI / 180;
  6791. };
  6792. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6793. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6794. var output = "";
  6795. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6796. var i = 0;
  6797. var bytes = new Uint8Array(buffer);
  6798. while (i < bytes.length) {
  6799. chr1 = bytes[i++];
  6800. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6801. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6802. enc1 = chr1 >> 2;
  6803. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6804. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6805. enc4 = chr3 & 63;
  6806. if (isNaN(chr2)) {
  6807. enc3 = enc4 = 64;
  6808. }
  6809. else if (isNaN(chr3)) {
  6810. enc4 = 64;
  6811. }
  6812. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6813. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6814. }
  6815. return "data:image/png;base64," + output;
  6816. };
  6817. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6818. if (bias === void 0) { bias = null; }
  6819. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6820. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6821. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6822. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6823. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6824. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6825. }
  6826. if (bias) {
  6827. minimum.x -= minimum.x * bias.x + bias.y;
  6828. minimum.y -= minimum.y * bias.x + bias.y;
  6829. minimum.z -= minimum.z * bias.x + bias.y;
  6830. maximum.x += maximum.x * bias.x + bias.y;
  6831. maximum.y += maximum.y * bias.x + bias.y;
  6832. maximum.z += maximum.z * bias.x + bias.y;
  6833. }
  6834. return {
  6835. minimum: minimum,
  6836. maximum: maximum
  6837. };
  6838. };
  6839. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6840. if (bias === void 0) { bias = null; }
  6841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6843. if (!stride) {
  6844. stride = 3;
  6845. }
  6846. for (var index = start; index < start + count; index++) {
  6847. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6848. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6849. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6850. }
  6851. if (bias) {
  6852. minimum.x -= minimum.x * bias.x + bias.y;
  6853. minimum.y -= minimum.y * bias.x + bias.y;
  6854. minimum.z -= minimum.z * bias.x + bias.y;
  6855. maximum.x += maximum.x * bias.x + bias.y;
  6856. maximum.y += maximum.y * bias.x + bias.y;
  6857. maximum.z += maximum.z * bias.x + bias.y;
  6858. }
  6859. return {
  6860. minimum: minimum,
  6861. maximum: maximum
  6862. };
  6863. };
  6864. Tools.Vector2ArrayFeeder = function (array) {
  6865. return function (index) {
  6866. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6867. var length = isFloatArray ? array.length / 2 : array.length;
  6868. if (index >= length) {
  6869. return null;
  6870. }
  6871. if (isFloatArray) {
  6872. var fa = array;
  6873. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6874. }
  6875. var a = array;
  6876. return a[index];
  6877. };
  6878. };
  6879. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6880. if (bias === void 0) { bias = null; }
  6881. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6882. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6883. var i = 0;
  6884. var cur = feeder(i++);
  6885. while (cur) {
  6886. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6887. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6888. cur = feeder(i++);
  6889. }
  6890. if (bias) {
  6891. minimum.x -= minimum.x * bias.x + bias.y;
  6892. minimum.y -= minimum.y * bias.x + bias.y;
  6893. maximum.x += maximum.x * bias.x + bias.y;
  6894. maximum.y += maximum.y * bias.x + bias.y;
  6895. }
  6896. return {
  6897. minimum: minimum,
  6898. maximum: maximum
  6899. };
  6900. };
  6901. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6902. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6903. return null;
  6904. return Array.isArray(obj) ? obj : [obj];
  6905. };
  6906. // Misc.
  6907. Tools.GetPointerPrefix = function () {
  6908. var eventPrefix = "pointer";
  6909. // Check if pointer events are supported
  6910. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6911. eventPrefix = "mouse";
  6912. }
  6913. return eventPrefix;
  6914. };
  6915. /**
  6916. * @param func - the function to be called
  6917. * @param requester - the object that will request the next frame. Falls back to window.
  6918. */
  6919. Tools.QueueNewFrame = function (func, requester) {
  6920. if (!Tools.IsWindowObjectExist()) {
  6921. return setTimeout(func, 16);
  6922. }
  6923. if (!requester) {
  6924. requester = window;
  6925. }
  6926. if (requester.requestAnimationFrame) {
  6927. return requester.requestAnimationFrame(func);
  6928. }
  6929. else if (requester.msRequestAnimationFrame) {
  6930. return requester.msRequestAnimationFrame(func);
  6931. }
  6932. else if (requester.webkitRequestAnimationFrame) {
  6933. return requester.webkitRequestAnimationFrame(func);
  6934. }
  6935. else if (requester.mozRequestAnimationFrame) {
  6936. return requester.mozRequestAnimationFrame(func);
  6937. }
  6938. else if (requester.oRequestAnimationFrame) {
  6939. return requester.oRequestAnimationFrame(func);
  6940. }
  6941. else {
  6942. return window.setTimeout(func, 16);
  6943. }
  6944. };
  6945. Tools.RequestFullscreen = function (element) {
  6946. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6947. if (!requestFunction)
  6948. return;
  6949. requestFunction.call(element);
  6950. };
  6951. Tools.ExitFullscreen = function () {
  6952. if (document.exitFullscreen) {
  6953. document.exitFullscreen();
  6954. }
  6955. else if (document.mozCancelFullScreen) {
  6956. document.mozCancelFullScreen();
  6957. }
  6958. else if (document.webkitCancelFullScreen) {
  6959. document.webkitCancelFullScreen();
  6960. }
  6961. else if (document.msCancelFullScreen) {
  6962. document.msCancelFullScreen();
  6963. }
  6964. };
  6965. Tools.SetCorsBehavior = function (url, element) {
  6966. if (url && url.indexOf("data:") === 0) {
  6967. return;
  6968. }
  6969. if (Tools.CorsBehavior) {
  6970. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6971. element.crossOrigin = Tools.CorsBehavior;
  6972. }
  6973. else {
  6974. var result = Tools.CorsBehavior(url);
  6975. if (result) {
  6976. element.crossOrigin = result;
  6977. }
  6978. }
  6979. }
  6980. };
  6981. // External files
  6982. Tools.CleanUrl = function (url) {
  6983. url = url.replace(/#/mg, "%23");
  6984. return url;
  6985. };
  6986. Tools.LoadImage = function (url, onLoad, onError, database) {
  6987. if (url instanceof ArrayBuffer) {
  6988. url = Tools.EncodeArrayBufferTobase64(url);
  6989. }
  6990. url = Tools.CleanUrl(url);
  6991. url = Tools.PreprocessUrl(url);
  6992. var img = new Image();
  6993. Tools.SetCorsBehavior(url, img);
  6994. img.onload = function () {
  6995. onLoad(img);
  6996. };
  6997. img.onerror = function (err) {
  6998. Tools.Error("Error while trying to load image: " + url);
  6999. if (onError) {
  7000. onError("Error while trying to load image: " + url, err);
  7001. }
  7002. };
  7003. var noIndexedDB = function () {
  7004. img.src = url;
  7005. };
  7006. var loadFromIndexedDB = function () {
  7007. if (database) {
  7008. database.loadImageFromDB(url, img);
  7009. }
  7010. };
  7011. //ANY database to do!
  7012. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7013. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7014. }
  7015. else {
  7016. if (url.indexOf("file:") !== -1) {
  7017. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7018. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7019. try {
  7020. var blobURL;
  7021. try {
  7022. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7023. }
  7024. catch (ex) {
  7025. // Chrome doesn't support oneTimeOnly parameter
  7026. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7027. }
  7028. img.src = blobURL;
  7029. }
  7030. catch (e) {
  7031. img.src = "";
  7032. }
  7033. return img;
  7034. }
  7035. }
  7036. noIndexedDB();
  7037. }
  7038. return img;
  7039. };
  7040. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7041. url = Tools.CleanUrl(url);
  7042. url = Tools.PreprocessUrl(url);
  7043. // If file and file input are set
  7044. if (url.indexOf("file:") !== -1) {
  7045. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7046. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7047. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7048. }
  7049. }
  7050. var loadUrl = Tools.BaseUrl + url;
  7051. var aborted = false;
  7052. var fileRequest = {
  7053. onCompleteObservable: new BABYLON.Observable(),
  7054. abort: function () { return aborted = true; },
  7055. };
  7056. var requestFile = function () {
  7057. var request = new XMLHttpRequest();
  7058. var retryHandle = null;
  7059. fileRequest.abort = function () {
  7060. aborted = true;
  7061. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7062. request.abort();
  7063. }
  7064. if (retryHandle !== null) {
  7065. clearTimeout(retryHandle);
  7066. retryHandle = null;
  7067. }
  7068. };
  7069. var retryLoop = function (retryIndex) {
  7070. request.open('GET', loadUrl, true);
  7071. if (useArrayBuffer) {
  7072. request.responseType = "arraybuffer";
  7073. }
  7074. if (onProgress) {
  7075. request.addEventListener("progress", onProgress);
  7076. }
  7077. var onLoadEnd = function () {
  7078. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7079. };
  7080. request.addEventListener("loadend", onLoadEnd);
  7081. var onReadyStateChange = function () {
  7082. if (aborted) {
  7083. return;
  7084. }
  7085. // In case of undefined state in some browsers.
  7086. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7087. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7088. request.removeEventListener("readystatechange", onReadyStateChange);
  7089. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7090. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7091. return;
  7092. }
  7093. var retryStrategy = Tools.DefaultRetryStrategy;
  7094. if (retryStrategy) {
  7095. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7096. if (waitTime !== -1) {
  7097. // Prevent the request from completing for retry.
  7098. request.removeEventListener("loadend", onLoadEnd);
  7099. request = new XMLHttpRequest();
  7100. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7101. return;
  7102. }
  7103. }
  7104. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7105. if (onError) {
  7106. onError(request, e);
  7107. }
  7108. else {
  7109. throw e;
  7110. }
  7111. }
  7112. };
  7113. request.addEventListener("readystatechange", onReadyStateChange);
  7114. request.send();
  7115. };
  7116. retryLoop(0);
  7117. };
  7118. // Caching all files
  7119. if (database && database.enableSceneOffline) {
  7120. var noIndexedDB_1 = function () {
  7121. if (!aborted) {
  7122. requestFile();
  7123. }
  7124. };
  7125. var loadFromIndexedDB = function () {
  7126. // TODO: database needs to support aborting and should return a IFileRequest
  7127. if (aborted) {
  7128. return;
  7129. }
  7130. if (database) {
  7131. database.loadFileFromDB(url, function (data) {
  7132. if (!aborted) {
  7133. onSuccess(data);
  7134. }
  7135. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7136. }, onProgress ? function (event) {
  7137. if (!aborted) {
  7138. onProgress(event);
  7139. }
  7140. } : undefined, noIndexedDB_1, useArrayBuffer);
  7141. }
  7142. };
  7143. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7144. }
  7145. else {
  7146. requestFile();
  7147. }
  7148. return fileRequest;
  7149. };
  7150. /**
  7151. * Load a script (identified by an url). When the url returns, the
  7152. * content of this file is added into a new script element, attached to the DOM (body element)
  7153. */
  7154. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7155. var head = document.getElementsByTagName('head')[0];
  7156. var script = document.createElement('script');
  7157. script.type = 'text/javascript';
  7158. script.src = scriptUrl;
  7159. script.onload = function () {
  7160. if (onSuccess) {
  7161. onSuccess();
  7162. }
  7163. };
  7164. script.onerror = function (e) {
  7165. if (onError) {
  7166. onError("Unable to load script", e);
  7167. }
  7168. };
  7169. head.appendChild(script);
  7170. };
  7171. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7172. var reader = new FileReader();
  7173. var request = {
  7174. onCompleteObservable: new BABYLON.Observable(),
  7175. abort: function () { return reader.abort(); },
  7176. };
  7177. reader.onloadend = function (e) {
  7178. request.onCompleteObservable.notifyObservers(request);
  7179. };
  7180. reader.onload = function (e) {
  7181. //target doesn't have result from ts 1.3
  7182. callback(e.target['result']);
  7183. };
  7184. reader.onprogress = progressCallback;
  7185. reader.readAsDataURL(fileToLoad);
  7186. return request;
  7187. };
  7188. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7189. var reader = new FileReader();
  7190. var request = {
  7191. onCompleteObservable: new BABYLON.Observable(),
  7192. abort: function () { return reader.abort(); },
  7193. };
  7194. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7195. reader.onerror = function (e) {
  7196. Tools.Log("Error while reading file: " + fileToLoad.name);
  7197. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7198. };
  7199. reader.onload = function (e) {
  7200. //target doesn't have result from ts 1.3
  7201. callback(e.target['result']);
  7202. };
  7203. if (progressCallBack) {
  7204. reader.onprogress = progressCallBack;
  7205. }
  7206. if (!useArrayBuffer) {
  7207. // Asynchronous read
  7208. reader.readAsText(fileToLoad);
  7209. }
  7210. else {
  7211. reader.readAsArrayBuffer(fileToLoad);
  7212. }
  7213. return request;
  7214. };
  7215. //returns a downloadable url to a file content.
  7216. Tools.FileAsURL = function (content) {
  7217. var fileBlob = new Blob([content]);
  7218. var url = window.URL || window.webkitURL;
  7219. var link = url.createObjectURL(fileBlob);
  7220. return link;
  7221. };
  7222. // Misc.
  7223. Tools.Format = function (value, decimals) {
  7224. if (decimals === void 0) { decimals = 2; }
  7225. return value.toFixed(decimals);
  7226. };
  7227. Tools.CheckExtends = function (v, min, max) {
  7228. if (v.x < min.x)
  7229. min.x = v.x;
  7230. if (v.y < min.y)
  7231. min.y = v.y;
  7232. if (v.z < min.z)
  7233. min.z = v.z;
  7234. if (v.x > max.x)
  7235. max.x = v.x;
  7236. if (v.y > max.y)
  7237. max.y = v.y;
  7238. if (v.z > max.z)
  7239. max.z = v.z;
  7240. };
  7241. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7242. for (var prop in source) {
  7243. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7244. continue;
  7245. }
  7246. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7247. continue;
  7248. }
  7249. var sourceValue = source[prop];
  7250. var typeOfSourceValue = typeof sourceValue;
  7251. if (typeOfSourceValue === "function") {
  7252. continue;
  7253. }
  7254. if (typeOfSourceValue === "object") {
  7255. if (sourceValue instanceof Array) {
  7256. destination[prop] = [];
  7257. if (sourceValue.length > 0) {
  7258. if (typeof sourceValue[0] == "object") {
  7259. for (var index = 0; index < sourceValue.length; index++) {
  7260. var clonedValue = cloneValue(sourceValue[index], destination);
  7261. if (destination[prop].indexOf(clonedValue) === -1) {
  7262. destination[prop].push(clonedValue);
  7263. }
  7264. }
  7265. }
  7266. else {
  7267. destination[prop] = sourceValue.slice(0);
  7268. }
  7269. }
  7270. }
  7271. else {
  7272. destination[prop] = cloneValue(sourceValue, destination);
  7273. }
  7274. }
  7275. else {
  7276. destination[prop] = sourceValue;
  7277. }
  7278. }
  7279. };
  7280. Tools.IsEmpty = function (obj) {
  7281. for (var i in obj) {
  7282. if (obj.hasOwnProperty(i)) {
  7283. return false;
  7284. }
  7285. }
  7286. return true;
  7287. };
  7288. Tools.RegisterTopRootEvents = function (events) {
  7289. for (var index = 0; index < events.length; index++) {
  7290. var event = events[index];
  7291. window.addEventListener(event.name, event.handler, false);
  7292. try {
  7293. if (window.parent) {
  7294. window.parent.addEventListener(event.name, event.handler, false);
  7295. }
  7296. }
  7297. catch (e) {
  7298. // Silently fails...
  7299. }
  7300. }
  7301. };
  7302. Tools.UnregisterTopRootEvents = function (events) {
  7303. for (var index = 0; index < events.length; index++) {
  7304. var event = events[index];
  7305. window.removeEventListener(event.name, event.handler);
  7306. try {
  7307. if (window.parent) {
  7308. window.parent.removeEventListener(event.name, event.handler);
  7309. }
  7310. }
  7311. catch (e) {
  7312. // Silently fails...
  7313. }
  7314. }
  7315. };
  7316. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7317. if (mimeType === void 0) { mimeType = "image/png"; }
  7318. // Read the contents of the framebuffer
  7319. var numberOfChannelsByLine = width * 4;
  7320. var halfHeight = height / 2;
  7321. //Reading datas from WebGL
  7322. var data = engine.readPixels(0, 0, width, height);
  7323. //To flip image on Y axis.
  7324. for (var i = 0; i < halfHeight; i++) {
  7325. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7326. var currentCell = j + i * numberOfChannelsByLine;
  7327. var targetLine = height - i - 1;
  7328. var targetCell = j + targetLine * numberOfChannelsByLine;
  7329. var temp = data[currentCell];
  7330. data[currentCell] = data[targetCell];
  7331. data[targetCell] = temp;
  7332. }
  7333. }
  7334. // Create a 2D canvas to store the result
  7335. if (!screenshotCanvas) {
  7336. screenshotCanvas = document.createElement('canvas');
  7337. }
  7338. screenshotCanvas.width = width;
  7339. screenshotCanvas.height = height;
  7340. var context = screenshotCanvas.getContext('2d');
  7341. if (context) {
  7342. // Copy the pixels to a 2D canvas
  7343. var imageData = context.createImageData(width, height);
  7344. var castData = (imageData.data);
  7345. castData.set(data);
  7346. context.putImageData(imageData, 0, 0);
  7347. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7348. }
  7349. };
  7350. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7351. if (mimeType === void 0) { mimeType = "image/png"; }
  7352. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7353. if (successCallback) {
  7354. successCallback(base64Image);
  7355. }
  7356. else {
  7357. // We need HTMLCanvasElement.toBlob for HD screenshots
  7358. if (!screenshotCanvas.toBlob) {
  7359. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7360. screenshotCanvas.toBlob = function (callback, type, quality) {
  7361. var _this = this;
  7362. setTimeout(function () {
  7363. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7364. for (var i = 0; i < len; i++) {
  7365. arr[i] = binStr.charCodeAt(i);
  7366. }
  7367. callback(new Blob([arr], { type: type || 'image/png' }));
  7368. });
  7369. };
  7370. }
  7371. screenshotCanvas.toBlob(function (blob) {
  7372. var url = URL.createObjectURL(blob);
  7373. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7374. if (("download" in document.createElement("a"))) {
  7375. var a = window.document.createElement("a");
  7376. a.href = url;
  7377. if (fileName) {
  7378. a.setAttribute("download", fileName);
  7379. }
  7380. else {
  7381. var date = new Date();
  7382. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7383. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7384. }
  7385. window.document.body.appendChild(a);
  7386. a.addEventListener("click", function () {
  7387. if (a.parentElement) {
  7388. a.parentElement.removeChild(a);
  7389. }
  7390. });
  7391. a.click();
  7392. }
  7393. else {
  7394. var newWindow = window.open("");
  7395. if (!newWindow)
  7396. return;
  7397. var img = newWindow.document.createElement("img");
  7398. img.onload = function () {
  7399. // no longer need to read the blob so it's revoked
  7400. URL.revokeObjectURL(url);
  7401. };
  7402. img.src = url;
  7403. newWindow.document.body.appendChild(img);
  7404. }
  7405. });
  7406. }
  7407. };
  7408. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7409. if (mimeType === void 0) { mimeType = "image/png"; }
  7410. var width;
  7411. var height;
  7412. // If a precision value is specified
  7413. if (size.precision) {
  7414. width = Math.round(engine.getRenderWidth() * size.precision);
  7415. height = Math.round(width / engine.getAspectRatio(camera));
  7416. }
  7417. else if (size.width && size.height) {
  7418. width = size.width;
  7419. height = size.height;
  7420. }
  7421. else if (size.width && !size.height) {
  7422. width = size.width;
  7423. height = Math.round(width / engine.getAspectRatio(camera));
  7424. }
  7425. else if (size.height && !size.width) {
  7426. height = size.height;
  7427. width = Math.round(height * engine.getAspectRatio(camera));
  7428. }
  7429. else if (!isNaN(size)) {
  7430. height = size;
  7431. width = size;
  7432. }
  7433. else {
  7434. Tools.Error("Invalid 'size' parameter !");
  7435. return;
  7436. }
  7437. if (!screenshotCanvas) {
  7438. screenshotCanvas = document.createElement('canvas');
  7439. }
  7440. screenshotCanvas.width = width;
  7441. screenshotCanvas.height = height;
  7442. var renderContext = screenshotCanvas.getContext("2d");
  7443. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7444. var newWidth = width;
  7445. var newHeight = newWidth / ratio;
  7446. if (newHeight > height) {
  7447. newHeight = height;
  7448. newWidth = newHeight * ratio;
  7449. }
  7450. var offsetX = Math.max(0, width - newWidth) / 2;
  7451. var offsetY = Math.max(0, height - newHeight) / 2;
  7452. var renderingCanvas = engine.getRenderingCanvas();
  7453. if (renderContext && renderingCanvas) {
  7454. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7455. }
  7456. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7457. };
  7458. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7459. if (mimeType === void 0) { mimeType = "image/png"; }
  7460. if (samples === void 0) { samples = 1; }
  7461. if (antialiasing === void 0) { antialiasing = false; }
  7462. var width;
  7463. var height;
  7464. //If a precision value is specified
  7465. if (size.precision) {
  7466. width = Math.round(engine.getRenderWidth() * size.precision);
  7467. height = Math.round(width / engine.getAspectRatio(camera));
  7468. size = { width: width, height: height };
  7469. }
  7470. else if (size.width && size.height) {
  7471. width = size.width;
  7472. height = size.height;
  7473. }
  7474. else if (size.width && !size.height) {
  7475. width = size.width;
  7476. height = Math.round(width / engine.getAspectRatio(camera));
  7477. size = { width: width, height: height };
  7478. }
  7479. else if (size.height && !size.width) {
  7480. height = size.height;
  7481. width = Math.round(height * engine.getAspectRatio(camera));
  7482. size = { width: width, height: height };
  7483. }
  7484. else if (!isNaN(size)) {
  7485. height = size;
  7486. width = size;
  7487. }
  7488. else {
  7489. Tools.Error("Invalid 'size' parameter !");
  7490. return;
  7491. }
  7492. var scene = camera.getScene();
  7493. var previousCamera = null;
  7494. if (scene.activeCamera !== camera) {
  7495. previousCamera = scene.activeCamera;
  7496. scene.activeCamera = camera;
  7497. }
  7498. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7499. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7500. texture.renderList = null;
  7501. texture.samples = samples;
  7502. if (antialiasing) {
  7503. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7504. }
  7505. texture.onAfterRenderObservable.add(function () {
  7506. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7507. });
  7508. scene.incrementRenderId();
  7509. scene.resetCachedMaterial();
  7510. texture.render(true);
  7511. texture.dispose();
  7512. if (previousCamera) {
  7513. scene.activeCamera = previousCamera;
  7514. }
  7515. camera.getProjectionMatrix(true); // Force cache refresh;
  7516. };
  7517. // XHR response validator for local file scenario
  7518. Tools.ValidateXHRData = function (xhr, dataType) {
  7519. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7520. if (dataType === void 0) { dataType = 7; }
  7521. try {
  7522. if (dataType & 1) {
  7523. if (xhr.responseText && xhr.responseText.length > 0) {
  7524. return true;
  7525. }
  7526. else if (dataType === 1) {
  7527. return false;
  7528. }
  7529. }
  7530. if (dataType & 2) {
  7531. // Check header width and height since there is no "TGA" magic number
  7532. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7533. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7534. return true;
  7535. }
  7536. else if (dataType === 2) {
  7537. return false;
  7538. }
  7539. }
  7540. if (dataType & 4) {
  7541. // Check for the "DDS" magic number
  7542. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7543. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7544. return true;
  7545. }
  7546. else {
  7547. return false;
  7548. }
  7549. }
  7550. }
  7551. catch (e) {
  7552. // Global protection
  7553. }
  7554. return false;
  7555. };
  7556. /**
  7557. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7558. * Be aware Math.random() could cause collisions, but:
  7559. * "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"
  7560. */
  7561. Tools.RandomId = function () {
  7562. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7563. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7564. return v.toString(16);
  7565. });
  7566. };
  7567. Object.defineProperty(Tools, "NoneLogLevel", {
  7568. get: function () {
  7569. return Tools._NoneLogLevel;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Tools, "MessageLogLevel", {
  7575. get: function () {
  7576. return Tools._MessageLogLevel;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Tools, "WarningLogLevel", {
  7582. get: function () {
  7583. return Tools._WarningLogLevel;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(Tools, "ErrorLogLevel", {
  7589. get: function () {
  7590. return Tools._ErrorLogLevel;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(Tools, "AllLogLevel", {
  7596. get: function () {
  7597. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Tools._AddLogEntry = function (entry) {
  7603. Tools._LogCache = entry + Tools._LogCache;
  7604. if (Tools.OnNewCacheEntry) {
  7605. Tools.OnNewCacheEntry(entry);
  7606. }
  7607. };
  7608. Tools._FormatMessage = function (message) {
  7609. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7610. var date = new Date();
  7611. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7612. };
  7613. Tools._LogDisabled = function (message) {
  7614. // nothing to do
  7615. };
  7616. Tools._LogEnabled = function (message) {
  7617. var formattedMessage = Tools._FormatMessage(message);
  7618. console.log("BJS - " + formattedMessage);
  7619. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7620. Tools._AddLogEntry(entry);
  7621. };
  7622. Tools._WarnDisabled = function (message) {
  7623. // nothing to do
  7624. };
  7625. Tools._WarnEnabled = function (message) {
  7626. var formattedMessage = Tools._FormatMessage(message);
  7627. console.warn("BJS - " + formattedMessage);
  7628. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7629. Tools._AddLogEntry(entry);
  7630. };
  7631. Tools._ErrorDisabled = function (message) {
  7632. // nothing to do
  7633. };
  7634. Tools._ErrorEnabled = function (message) {
  7635. Tools.errorsCount++;
  7636. var formattedMessage = Tools._FormatMessage(message);
  7637. console.error("BJS - " + formattedMessage);
  7638. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7639. Tools._AddLogEntry(entry);
  7640. };
  7641. Object.defineProperty(Tools, "LogCache", {
  7642. get: function () {
  7643. return Tools._LogCache;
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. Tools.ClearLogCache = function () {
  7649. Tools._LogCache = "";
  7650. Tools.errorsCount = 0;
  7651. };
  7652. Object.defineProperty(Tools, "LogLevels", {
  7653. set: function (level) {
  7654. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7655. Tools.Log = Tools._LogEnabled;
  7656. }
  7657. else {
  7658. Tools.Log = Tools._LogDisabled;
  7659. }
  7660. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7661. Tools.Warn = Tools._WarnEnabled;
  7662. }
  7663. else {
  7664. Tools.Warn = Tools._WarnDisabled;
  7665. }
  7666. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7667. Tools.Error = Tools._ErrorEnabled;
  7668. }
  7669. else {
  7670. Tools.Error = Tools._ErrorDisabled;
  7671. }
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Tools.IsWindowObjectExist = function () {
  7677. return (typeof window) !== "undefined";
  7678. };
  7679. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7680. get: function () {
  7681. return Tools._PerformanceNoneLogLevel;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7687. get: function () {
  7688. return Tools._PerformanceUserMarkLogLevel;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7694. get: function () {
  7695. return Tools._PerformanceConsoleLogLevel;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7701. set: function (level) {
  7702. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7703. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7704. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7705. return;
  7706. }
  7707. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7708. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7709. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7710. return;
  7711. }
  7712. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7713. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7719. };
  7720. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7721. };
  7722. Tools._StartUserMark = function (counterName, condition) {
  7723. if (condition === void 0) { condition = true; }
  7724. if (!Tools._performance) {
  7725. if (!Tools.IsWindowObjectExist()) {
  7726. return;
  7727. }
  7728. Tools._performance = window.performance;
  7729. }
  7730. if (!condition || !Tools._performance.mark) {
  7731. return;
  7732. }
  7733. Tools._performance.mark(counterName + "-Begin");
  7734. };
  7735. Tools._EndUserMark = function (counterName, condition) {
  7736. if (condition === void 0) { condition = true; }
  7737. if (!condition || !Tools._performance.mark) {
  7738. return;
  7739. }
  7740. Tools._performance.mark(counterName + "-End");
  7741. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7742. };
  7743. Tools._StartPerformanceConsole = function (counterName, condition) {
  7744. if (condition === void 0) { condition = true; }
  7745. if (!condition) {
  7746. return;
  7747. }
  7748. Tools._StartUserMark(counterName, condition);
  7749. if (console.time) {
  7750. console.time(counterName);
  7751. }
  7752. };
  7753. Tools._EndPerformanceConsole = function (counterName, condition) {
  7754. if (condition === void 0) { condition = true; }
  7755. if (!condition) {
  7756. return;
  7757. }
  7758. Tools._EndUserMark(counterName, condition);
  7759. if (console.time) {
  7760. console.timeEnd(counterName);
  7761. }
  7762. };
  7763. Object.defineProperty(Tools, "Now", {
  7764. get: function () {
  7765. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7766. return window.performance.now();
  7767. }
  7768. return new Date().getTime();
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. /**
  7774. * This method will return the name of the class used to create the instance of the given object.
  7775. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7776. * @param object the object to get the class name from
  7777. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7778. */
  7779. Tools.GetClassName = function (object, isType) {
  7780. if (isType === void 0) { isType = false; }
  7781. var name = null;
  7782. if (!isType && object.getClassName) {
  7783. name = object.getClassName();
  7784. }
  7785. else {
  7786. if (object instanceof Object) {
  7787. var classObj = isType ? object : Object.getPrototypeOf(object);
  7788. name = classObj.constructor["__bjsclassName__"];
  7789. }
  7790. if (!name) {
  7791. name = typeof object;
  7792. }
  7793. }
  7794. return name;
  7795. };
  7796. Tools.First = function (array, predicate) {
  7797. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7798. var el = array_1[_i];
  7799. if (predicate(el)) {
  7800. return el;
  7801. }
  7802. }
  7803. return null;
  7804. };
  7805. /**
  7806. * This method will return the name of the full name of the class, including its owning module (if any).
  7807. * 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).
  7808. * @param object the object to get the class name from
  7809. * @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.
  7810. */
  7811. Tools.getFullClassName = function (object, isType) {
  7812. if (isType === void 0) { isType = false; }
  7813. var className = null;
  7814. var moduleName = null;
  7815. if (!isType && object.getClassName) {
  7816. className = object.getClassName();
  7817. }
  7818. else {
  7819. if (object instanceof Object) {
  7820. var classObj = isType ? object : Object.getPrototypeOf(object);
  7821. className = classObj.constructor["__bjsclassName__"];
  7822. moduleName = classObj.constructor["__bjsmoduleName__"];
  7823. }
  7824. if (!className) {
  7825. className = typeof object;
  7826. }
  7827. }
  7828. if (!className) {
  7829. return null;
  7830. }
  7831. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7832. };
  7833. /**
  7834. * 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.
  7835. * @param array
  7836. */
  7837. Tools.arrayOrStringFeeder = function (array) {
  7838. return function (index) {
  7839. if (index >= array.length) {
  7840. return null;
  7841. }
  7842. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7843. if (val && val.getHashCode) {
  7844. val = val.getHashCode();
  7845. }
  7846. if (typeof val === "string") {
  7847. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7848. }
  7849. return val;
  7850. };
  7851. };
  7852. /**
  7853. * Compute the hashCode of a stream of number
  7854. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7855. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7856. * @return the hash code computed
  7857. */
  7858. Tools.hashCodeFromStream = function (feeder) {
  7859. // Based from here: http://stackoverflow.com/a/7616484/802124
  7860. var hash = 0;
  7861. var index = 0;
  7862. var chr = feeder(index++);
  7863. while (chr != null) {
  7864. hash = ((hash << 5) - hash) + chr;
  7865. hash |= 0; // Convert to 32bit integer
  7866. chr = feeder(index++);
  7867. }
  7868. return hash;
  7869. };
  7870. Tools.BaseUrl = "";
  7871. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7872. /**
  7873. * Default behaviour for cors in the application.
  7874. * It can be a string if the expected behavior is identical in the entire app.
  7875. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7876. */
  7877. Tools.CorsBehavior = "anonymous";
  7878. Tools.UseFallbackTexture = true;
  7879. /**
  7880. * Use this object to register external classes like custom textures or material
  7881. * to allow the laoders to instantiate them
  7882. */
  7883. Tools.RegisteredExternalClasses = {};
  7884. // Used in case of a texture loading problem
  7885. 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";
  7886. Tools.PreprocessUrl = function (url) {
  7887. return url;
  7888. };
  7889. // Logs
  7890. Tools._NoneLogLevel = 0;
  7891. Tools._MessageLogLevel = 1;
  7892. Tools._WarningLogLevel = 2;
  7893. Tools._ErrorLogLevel = 4;
  7894. Tools._LogCache = "";
  7895. Tools.errorsCount = 0;
  7896. Tools.Log = Tools._LogEnabled;
  7897. Tools.Warn = Tools._WarnEnabled;
  7898. Tools.Error = Tools._ErrorEnabled;
  7899. // Performances
  7900. Tools._PerformanceNoneLogLevel = 0;
  7901. Tools._PerformanceUserMarkLogLevel = 1;
  7902. Tools._PerformanceConsoleLogLevel = 2;
  7903. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7904. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7905. return Tools;
  7906. }());
  7907. BABYLON.Tools = Tools;
  7908. /**
  7909. * This class is used to track a performance counter which is number based.
  7910. * The user has access to many properties which give statistics of different nature
  7911. *
  7912. * The implementer can track two kinds of Performance Counter: time and count
  7913. * 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.
  7914. * 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.
  7915. */
  7916. var PerfCounter = /** @class */ (function () {
  7917. function PerfCounter() {
  7918. this._startMonitoringTime = 0;
  7919. this._min = 0;
  7920. this._max = 0;
  7921. this._average = 0;
  7922. this._lastSecAverage = 0;
  7923. this._current = 0;
  7924. this._totalValueCount = 0;
  7925. this._totalAccumulated = 0;
  7926. this._lastSecAccumulated = 0;
  7927. this._lastSecTime = 0;
  7928. this._lastSecValueCount = 0;
  7929. }
  7930. Object.defineProperty(PerfCounter.prototype, "min", {
  7931. /**
  7932. * Returns the smallest value ever
  7933. */
  7934. get: function () {
  7935. return this._min;
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(PerfCounter.prototype, "max", {
  7941. /**
  7942. * Returns the biggest value ever
  7943. */
  7944. get: function () {
  7945. return this._max;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. Object.defineProperty(PerfCounter.prototype, "average", {
  7951. /**
  7952. * Returns the average value since the performance counter is running
  7953. */
  7954. get: function () {
  7955. return this._average;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7961. /**
  7962. * Returns the average value of the last second the counter was monitored
  7963. */
  7964. get: function () {
  7965. return this._lastSecAverage;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(PerfCounter.prototype, "current", {
  7971. /**
  7972. * Returns the current value
  7973. */
  7974. get: function () {
  7975. return this._current;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(PerfCounter.prototype, "total", {
  7981. get: function () {
  7982. return this._totalAccumulated;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(PerfCounter.prototype, "count", {
  7988. get: function () {
  7989. return this._totalValueCount;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. /**
  7995. * Call this method to start monitoring a new frame.
  7996. * 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.
  7997. */
  7998. PerfCounter.prototype.fetchNewFrame = function () {
  7999. this._totalValueCount++;
  8000. this._current = 0;
  8001. this._lastSecValueCount++;
  8002. };
  8003. /**
  8004. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8005. * @param newCount the count value to add to the monitored count
  8006. * @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.
  8007. */
  8008. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8009. if (!PerfCounter.Enabled) {
  8010. return;
  8011. }
  8012. this._current += newCount;
  8013. if (fetchResult) {
  8014. this._fetchResult();
  8015. }
  8016. };
  8017. /**
  8018. * Start monitoring this performance counter
  8019. */
  8020. PerfCounter.prototype.beginMonitoring = function () {
  8021. if (!PerfCounter.Enabled) {
  8022. return;
  8023. }
  8024. this._startMonitoringTime = Tools.Now;
  8025. };
  8026. /**
  8027. * Compute the time lapsed since the previous beginMonitoring() call.
  8028. * @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
  8029. */
  8030. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8031. if (newFrame === void 0) { newFrame = true; }
  8032. if (!PerfCounter.Enabled) {
  8033. return;
  8034. }
  8035. if (newFrame) {
  8036. this.fetchNewFrame();
  8037. }
  8038. var currentTime = Tools.Now;
  8039. this._current = currentTime - this._startMonitoringTime;
  8040. if (newFrame) {
  8041. this._fetchResult();
  8042. }
  8043. };
  8044. PerfCounter.prototype._fetchResult = function () {
  8045. this._totalAccumulated += this._current;
  8046. this._lastSecAccumulated += this._current;
  8047. // Min/Max update
  8048. this._min = Math.min(this._min, this._current);
  8049. this._max = Math.max(this._max, this._current);
  8050. this._average = this._totalAccumulated / this._totalValueCount;
  8051. // Reset last sec?
  8052. var now = Tools.Now;
  8053. if ((now - this._lastSecTime) > 1000) {
  8054. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8055. this._lastSecTime = now;
  8056. this._lastSecAccumulated = 0;
  8057. this._lastSecValueCount = 0;
  8058. }
  8059. };
  8060. PerfCounter.Enabled = true;
  8061. return PerfCounter;
  8062. }());
  8063. BABYLON.PerfCounter = PerfCounter;
  8064. /**
  8065. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8066. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8067. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8068. * @param name The name of the class, case should be preserved
  8069. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8070. */
  8071. function className(name, module) {
  8072. return function (target) {
  8073. target["__bjsclassName__"] = name;
  8074. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8075. };
  8076. }
  8077. BABYLON.className = className;
  8078. /**
  8079. * An implementation of a loop for asynchronous functions.
  8080. */
  8081. var AsyncLoop = /** @class */ (function () {
  8082. /**
  8083. * Constroctor.
  8084. * @param iterations the number of iterations.
  8085. * @param _fn the function to run each iteration
  8086. * @param _successCallback the callback that will be called upon succesful execution
  8087. * @param offset starting offset.
  8088. */
  8089. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8090. if (offset === void 0) { offset = 0; }
  8091. this.iterations = iterations;
  8092. this._fn = _fn;
  8093. this._successCallback = _successCallback;
  8094. this.index = offset - 1;
  8095. this._done = false;
  8096. }
  8097. /**
  8098. * Execute the next iteration. Must be called after the last iteration was finished.
  8099. */
  8100. AsyncLoop.prototype.executeNext = function () {
  8101. if (!this._done) {
  8102. if (this.index + 1 < this.iterations) {
  8103. ++this.index;
  8104. this._fn(this);
  8105. }
  8106. else {
  8107. this.breakLoop();
  8108. }
  8109. }
  8110. };
  8111. /**
  8112. * Break the loop and run the success callback.
  8113. */
  8114. AsyncLoop.prototype.breakLoop = function () {
  8115. this._done = true;
  8116. this._successCallback();
  8117. };
  8118. /**
  8119. * Helper function
  8120. */
  8121. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8122. if (offset === void 0) { offset = 0; }
  8123. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8124. loop.executeNext();
  8125. return loop;
  8126. };
  8127. /**
  8128. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8129. * @param iterations total number of iterations
  8130. * @param syncedIterations number of synchronous iterations in each async iteration.
  8131. * @param fn the function to call each iteration.
  8132. * @param callback a success call back that will be called when iterating stops.
  8133. * @param breakFunction a break condition (optional)
  8134. * @param timeout timeout settings for the setTimeout function. default - 0.
  8135. * @constructor
  8136. */
  8137. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8138. if (timeout === void 0) { timeout = 0; }
  8139. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8140. if (breakFunction && breakFunction())
  8141. loop.breakLoop();
  8142. else {
  8143. setTimeout(function () {
  8144. for (var i = 0; i < syncedIterations; ++i) {
  8145. var iteration = (loop.index * syncedIterations) + i;
  8146. if (iteration >= iterations)
  8147. break;
  8148. fn(iteration);
  8149. if (breakFunction && breakFunction()) {
  8150. loop.breakLoop();
  8151. break;
  8152. }
  8153. }
  8154. loop.executeNext();
  8155. }, timeout);
  8156. }
  8157. }, callback);
  8158. };
  8159. return AsyncLoop;
  8160. }());
  8161. BABYLON.AsyncLoop = AsyncLoop;
  8162. })(BABYLON || (BABYLON = {}));
  8163. //# sourceMappingURL=babylon.tools.js.map
  8164. var BABYLON;
  8165. (function (BABYLON) {
  8166. var _AlphaState = /** @class */ (function () {
  8167. /**
  8168. * Initializes the state.
  8169. */
  8170. function _AlphaState() {
  8171. this._isAlphaBlendDirty = false;
  8172. this._isBlendFunctionParametersDirty = false;
  8173. this._isBlendEquationParametersDirty = false;
  8174. this._isBlendConstantsDirty = false;
  8175. this._alphaBlend = false;
  8176. this._blendFunctionParameters = new Array(4);
  8177. this._blendEquationParameters = new Array(2);
  8178. this._blendConstants = new Array(4);
  8179. this.reset();
  8180. }
  8181. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8182. get: function () {
  8183. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8189. get: function () {
  8190. return this._alphaBlend;
  8191. },
  8192. set: function (value) {
  8193. if (this._alphaBlend === value) {
  8194. return;
  8195. }
  8196. this._alphaBlend = value;
  8197. this._isAlphaBlendDirty = true;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8203. if (this._blendConstants[0] === r &&
  8204. this._blendConstants[1] === g &&
  8205. this._blendConstants[2] === b &&
  8206. this._blendConstants[3] === a) {
  8207. return;
  8208. }
  8209. this._blendConstants[0] = r;
  8210. this._blendConstants[1] = g;
  8211. this._blendConstants[2] = b;
  8212. this._blendConstants[3] = a;
  8213. this._isBlendConstantsDirty = true;
  8214. };
  8215. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8216. if (this._blendFunctionParameters[0] === value0 &&
  8217. this._blendFunctionParameters[1] === value1 &&
  8218. this._blendFunctionParameters[2] === value2 &&
  8219. this._blendFunctionParameters[3] === value3) {
  8220. return;
  8221. }
  8222. this._blendFunctionParameters[0] = value0;
  8223. this._blendFunctionParameters[1] = value1;
  8224. this._blendFunctionParameters[2] = value2;
  8225. this._blendFunctionParameters[3] = value3;
  8226. this._isBlendFunctionParametersDirty = true;
  8227. };
  8228. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8229. if (this._blendEquationParameters[0] === rgb &&
  8230. this._blendEquationParameters[1] === alpha) {
  8231. return;
  8232. }
  8233. this._blendEquationParameters[0] = rgb;
  8234. this._blendEquationParameters[1] = alpha;
  8235. this._isBlendEquationParametersDirty = true;
  8236. };
  8237. _AlphaState.prototype.reset = function () {
  8238. this._alphaBlend = false;
  8239. this._blendFunctionParameters[0] = null;
  8240. this._blendFunctionParameters[1] = null;
  8241. this._blendFunctionParameters[2] = null;
  8242. this._blendFunctionParameters[3] = null;
  8243. this._blendEquationParameters[0] = null;
  8244. this._blendEquationParameters[1] = null;
  8245. this._blendConstants[0] = null;
  8246. this._blendConstants[1] = null;
  8247. this._blendConstants[2] = null;
  8248. this._blendConstants[3] = null;
  8249. this._isAlphaBlendDirty = true;
  8250. this._isBlendFunctionParametersDirty = false;
  8251. this._isBlendEquationParametersDirty = false;
  8252. this._isBlendConstantsDirty = false;
  8253. };
  8254. _AlphaState.prototype.apply = function (gl) {
  8255. if (!this.isDirty) {
  8256. return;
  8257. }
  8258. // Alpha blend
  8259. if (this._isAlphaBlendDirty) {
  8260. if (this._alphaBlend) {
  8261. gl.enable(gl.BLEND);
  8262. }
  8263. else {
  8264. gl.disable(gl.BLEND);
  8265. }
  8266. this._isAlphaBlendDirty = false;
  8267. }
  8268. // Alpha function
  8269. if (this._isBlendFunctionParametersDirty) {
  8270. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8271. this._isBlendFunctionParametersDirty = false;
  8272. }
  8273. // Alpha equation
  8274. if (this._isBlendEquationParametersDirty) {
  8275. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8276. this._isBlendEquationParametersDirty = false;
  8277. }
  8278. // Constants
  8279. if (this._isBlendConstantsDirty) {
  8280. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8281. this._isBlendConstantsDirty = false;
  8282. }
  8283. };
  8284. return _AlphaState;
  8285. }());
  8286. BABYLON._AlphaState = _AlphaState;
  8287. })(BABYLON || (BABYLON = {}));
  8288. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. var _DepthCullingState = /** @class */ (function () {
  8292. /**
  8293. * Initializes the state.
  8294. */
  8295. function _DepthCullingState() {
  8296. this._isDepthTestDirty = false;
  8297. this._isDepthMaskDirty = false;
  8298. this._isDepthFuncDirty = false;
  8299. this._isCullFaceDirty = false;
  8300. this._isCullDirty = false;
  8301. this._isZOffsetDirty = false;
  8302. this._isFrontFaceDirty = false;
  8303. this.reset();
  8304. }
  8305. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8306. get: function () {
  8307. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8313. get: function () {
  8314. return this._zOffset;
  8315. },
  8316. set: function (value) {
  8317. if (this._zOffset === value) {
  8318. return;
  8319. }
  8320. this._zOffset = value;
  8321. this._isZOffsetDirty = true;
  8322. },
  8323. enumerable: true,
  8324. configurable: true
  8325. });
  8326. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8327. get: function () {
  8328. return this._cullFace;
  8329. },
  8330. set: function (value) {
  8331. if (this._cullFace === value) {
  8332. return;
  8333. }
  8334. this._cullFace = value;
  8335. this._isCullFaceDirty = true;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8341. get: function () {
  8342. return this._cull;
  8343. },
  8344. set: function (value) {
  8345. if (this._cull === value) {
  8346. return;
  8347. }
  8348. this._cull = value;
  8349. this._isCullDirty = true;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8355. get: function () {
  8356. return this._depthFunc;
  8357. },
  8358. set: function (value) {
  8359. if (this._depthFunc === value) {
  8360. return;
  8361. }
  8362. this._depthFunc = value;
  8363. this._isDepthFuncDirty = true;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8369. get: function () {
  8370. return this._depthMask;
  8371. },
  8372. set: function (value) {
  8373. if (this._depthMask === value) {
  8374. return;
  8375. }
  8376. this._depthMask = value;
  8377. this._isDepthMaskDirty = true;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8383. get: function () {
  8384. return this._depthTest;
  8385. },
  8386. set: function (value) {
  8387. if (this._depthTest === value) {
  8388. return;
  8389. }
  8390. this._depthTest = value;
  8391. this._isDepthTestDirty = true;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8397. get: function () {
  8398. return this._frontFace;
  8399. },
  8400. set: function (value) {
  8401. if (this._frontFace === value) {
  8402. return;
  8403. }
  8404. this._frontFace = value;
  8405. this._isFrontFaceDirty = true;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. _DepthCullingState.prototype.reset = function () {
  8411. this._depthMask = true;
  8412. this._depthTest = true;
  8413. this._depthFunc = null;
  8414. this._cullFace = null;
  8415. this._cull = null;
  8416. this._zOffset = 0;
  8417. this._frontFace = null;
  8418. this._isDepthTestDirty = true;
  8419. this._isDepthMaskDirty = true;
  8420. this._isDepthFuncDirty = false;
  8421. this._isCullFaceDirty = false;
  8422. this._isCullDirty = false;
  8423. this._isZOffsetDirty = false;
  8424. this._isFrontFaceDirty = false;
  8425. };
  8426. _DepthCullingState.prototype.apply = function (gl) {
  8427. if (!this.isDirty) {
  8428. return;
  8429. }
  8430. // Cull
  8431. if (this._isCullDirty) {
  8432. if (this.cull) {
  8433. gl.enable(gl.CULL_FACE);
  8434. }
  8435. else {
  8436. gl.disable(gl.CULL_FACE);
  8437. }
  8438. this._isCullDirty = false;
  8439. }
  8440. // Cull face
  8441. if (this._isCullFaceDirty) {
  8442. gl.cullFace(this.cullFace);
  8443. this._isCullFaceDirty = false;
  8444. }
  8445. // Depth mask
  8446. if (this._isDepthMaskDirty) {
  8447. gl.depthMask(this.depthMask);
  8448. this._isDepthMaskDirty = false;
  8449. }
  8450. // Depth test
  8451. if (this._isDepthTestDirty) {
  8452. if (this.depthTest) {
  8453. gl.enable(gl.DEPTH_TEST);
  8454. }
  8455. else {
  8456. gl.disable(gl.DEPTH_TEST);
  8457. }
  8458. this._isDepthTestDirty = false;
  8459. }
  8460. // Depth func
  8461. if (this._isDepthFuncDirty) {
  8462. gl.depthFunc(this.depthFunc);
  8463. this._isDepthFuncDirty = false;
  8464. }
  8465. // zOffset
  8466. if (this._isZOffsetDirty) {
  8467. if (this.zOffset) {
  8468. gl.enable(gl.POLYGON_OFFSET_FILL);
  8469. gl.polygonOffset(this.zOffset, 0);
  8470. }
  8471. else {
  8472. gl.disable(gl.POLYGON_OFFSET_FILL);
  8473. }
  8474. this._isZOffsetDirty = false;
  8475. }
  8476. // Front face
  8477. if (this._isFrontFaceDirty) {
  8478. gl.frontFace(this.frontFace);
  8479. this._isFrontFaceDirty = false;
  8480. }
  8481. };
  8482. return _DepthCullingState;
  8483. }());
  8484. BABYLON._DepthCullingState = _DepthCullingState;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.depthCullingState.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. var _StencilState = /** @class */ (function () {
  8490. function _StencilState() {
  8491. this._isStencilTestDirty = false;
  8492. this._isStencilMaskDirty = false;
  8493. this._isStencilFuncDirty = false;
  8494. this._isStencilOpDirty = false;
  8495. this.reset();
  8496. }
  8497. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8498. get: function () {
  8499. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8505. get: function () {
  8506. return this._stencilFunc;
  8507. },
  8508. set: function (value) {
  8509. if (this._stencilFunc === value) {
  8510. return;
  8511. }
  8512. this._stencilFunc = value;
  8513. this._isStencilFuncDirty = true;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8519. get: function () {
  8520. return this._stencilFuncRef;
  8521. },
  8522. set: function (value) {
  8523. if (this._stencilFuncRef === value) {
  8524. return;
  8525. }
  8526. this._stencilFuncRef = value;
  8527. this._isStencilFuncDirty = true;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8533. get: function () {
  8534. return this._stencilFuncMask;
  8535. },
  8536. set: function (value) {
  8537. if (this._stencilFuncMask === value) {
  8538. return;
  8539. }
  8540. this._stencilFuncMask = value;
  8541. this._isStencilFuncDirty = true;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8547. get: function () {
  8548. return this._stencilOpStencilFail;
  8549. },
  8550. set: function (value) {
  8551. if (this._stencilOpStencilFail === value) {
  8552. return;
  8553. }
  8554. this._stencilOpStencilFail = value;
  8555. this._isStencilOpDirty = true;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8561. get: function () {
  8562. return this._stencilOpDepthFail;
  8563. },
  8564. set: function (value) {
  8565. if (this._stencilOpDepthFail === value) {
  8566. return;
  8567. }
  8568. this._stencilOpDepthFail = value;
  8569. this._isStencilOpDirty = true;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8575. get: function () {
  8576. return this._stencilOpStencilDepthPass;
  8577. },
  8578. set: function (value) {
  8579. if (this._stencilOpStencilDepthPass === value) {
  8580. return;
  8581. }
  8582. this._stencilOpStencilDepthPass = value;
  8583. this._isStencilOpDirty = true;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8589. get: function () {
  8590. return this._stencilMask;
  8591. },
  8592. set: function (value) {
  8593. if (this._stencilMask === value) {
  8594. return;
  8595. }
  8596. this._stencilMask = value;
  8597. this._isStencilMaskDirty = true;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8603. get: function () {
  8604. return this._stencilTest;
  8605. },
  8606. set: function (value) {
  8607. if (this._stencilTest === value) {
  8608. return;
  8609. }
  8610. this._stencilTest = value;
  8611. this._isStencilTestDirty = true;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. _StencilState.prototype.reset = function () {
  8617. this._stencilTest = false;
  8618. this._stencilMask = 0xFF;
  8619. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8620. this._stencilFuncRef = 1;
  8621. this._stencilFuncMask = 0xFF;
  8622. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8623. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8624. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8625. this._isStencilTestDirty = true;
  8626. this._isStencilMaskDirty = true;
  8627. this._isStencilFuncDirty = true;
  8628. this._isStencilOpDirty = true;
  8629. };
  8630. _StencilState.prototype.apply = function (gl) {
  8631. if (!this.isDirty) {
  8632. return;
  8633. }
  8634. // Stencil test
  8635. if (this._isStencilTestDirty) {
  8636. if (this.stencilTest) {
  8637. gl.enable(gl.STENCIL_TEST);
  8638. }
  8639. else {
  8640. gl.disable(gl.STENCIL_TEST);
  8641. }
  8642. this._isStencilTestDirty = false;
  8643. }
  8644. // Stencil mask
  8645. if (this._isStencilMaskDirty) {
  8646. gl.stencilMask(this.stencilMask);
  8647. this._isStencilMaskDirty = false;
  8648. }
  8649. // Stencil func
  8650. if (this._isStencilFuncDirty) {
  8651. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8652. this._isStencilFuncDirty = false;
  8653. }
  8654. // Stencil op
  8655. if (this._isStencilOpDirty) {
  8656. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8657. this._isStencilOpDirty = false;
  8658. }
  8659. };
  8660. return _StencilState;
  8661. }());
  8662. BABYLON._StencilState = _StencilState;
  8663. })(BABYLON || (BABYLON = {}));
  8664. //# sourceMappingURL=babylon.stencilState.js.map
  8665. var BABYLON;
  8666. (function (BABYLON) {
  8667. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8668. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8669. };
  8670. var compileRawShader = function (gl, source, type) {
  8671. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8672. gl.shaderSource(shader, source);
  8673. gl.compileShader(shader);
  8674. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8675. var log = gl.getShaderInfoLog(shader);
  8676. if (log) {
  8677. throw new Error(log);
  8678. }
  8679. }
  8680. if (!shader) {
  8681. throw new Error("Something went wrong while compile the shader.");
  8682. }
  8683. return shader;
  8684. };
  8685. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8686. var magFilter = gl.NEAREST;
  8687. var minFilter = gl.NEAREST;
  8688. switch (samplingMode) {
  8689. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8690. magFilter = gl.LINEAR;
  8691. if (generateMipMaps) {
  8692. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8693. }
  8694. else {
  8695. minFilter = gl.LINEAR;
  8696. }
  8697. break;
  8698. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8699. magFilter = gl.LINEAR;
  8700. if (generateMipMaps) {
  8701. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8702. }
  8703. else {
  8704. minFilter = gl.LINEAR;
  8705. }
  8706. break;
  8707. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8708. magFilter = gl.NEAREST;
  8709. if (generateMipMaps) {
  8710. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8711. }
  8712. else {
  8713. minFilter = gl.NEAREST;
  8714. }
  8715. break;
  8716. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8717. magFilter = gl.NEAREST;
  8718. if (generateMipMaps) {
  8719. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8720. }
  8721. else {
  8722. minFilter = gl.NEAREST;
  8723. }
  8724. break;
  8725. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8726. magFilter = gl.NEAREST;
  8727. if (generateMipMaps) {
  8728. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8729. }
  8730. else {
  8731. minFilter = gl.LINEAR;
  8732. }
  8733. break;
  8734. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8735. magFilter = gl.NEAREST;
  8736. if (generateMipMaps) {
  8737. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8738. }
  8739. else {
  8740. minFilter = gl.LINEAR;
  8741. }
  8742. break;
  8743. case BABYLON.Texture.NEAREST_LINEAR:
  8744. magFilter = gl.NEAREST;
  8745. minFilter = gl.LINEAR;
  8746. break;
  8747. case BABYLON.Texture.NEAREST_NEAREST:
  8748. magFilter = gl.NEAREST;
  8749. minFilter = gl.NEAREST;
  8750. break;
  8751. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8752. magFilter = gl.LINEAR;
  8753. if (generateMipMaps) {
  8754. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8755. }
  8756. else {
  8757. minFilter = gl.NEAREST;
  8758. }
  8759. break;
  8760. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8761. magFilter = gl.LINEAR;
  8762. if (generateMipMaps) {
  8763. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8764. }
  8765. else {
  8766. minFilter = gl.NEAREST;
  8767. }
  8768. break;
  8769. case BABYLON.Texture.LINEAR_LINEAR:
  8770. magFilter = gl.LINEAR;
  8771. minFilter = gl.LINEAR;
  8772. break;
  8773. case BABYLON.Texture.LINEAR_NEAREST:
  8774. magFilter = gl.LINEAR;
  8775. minFilter = gl.NEAREST;
  8776. break;
  8777. }
  8778. return {
  8779. min: minFilter,
  8780. mag: magFilter
  8781. };
  8782. };
  8783. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8784. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8785. var img;
  8786. var onload = function () {
  8787. loadedImages[index] = img;
  8788. loadedImages._internalCount++;
  8789. if (scene) {
  8790. scene._removePendingData(img);
  8791. }
  8792. if (loadedImages._internalCount === 6) {
  8793. onfinish(loadedImages);
  8794. }
  8795. };
  8796. var onerror = function (message, exception) {
  8797. if (scene) {
  8798. scene._removePendingData(img);
  8799. }
  8800. if (onErrorCallBack) {
  8801. onErrorCallBack(message, exception);
  8802. }
  8803. };
  8804. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8805. if (scene) {
  8806. scene._addPendingData(img);
  8807. }
  8808. };
  8809. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8810. if (onError === void 0) { onError = null; }
  8811. var loadedImages = [];
  8812. loadedImages._internalCount = 0;
  8813. for (var index = 0; index < 6; index++) {
  8814. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8815. }
  8816. };
  8817. var BufferPointer = /** @class */ (function () {
  8818. function BufferPointer() {
  8819. }
  8820. return BufferPointer;
  8821. }());
  8822. var InstancingAttributeInfo = /** @class */ (function () {
  8823. function InstancingAttributeInfo() {
  8824. }
  8825. return InstancingAttributeInfo;
  8826. }());
  8827. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8828. /**
  8829. * Define options used to create a render target texture
  8830. */
  8831. var RenderTargetCreationOptions = /** @class */ (function () {
  8832. function RenderTargetCreationOptions() {
  8833. }
  8834. return RenderTargetCreationOptions;
  8835. }());
  8836. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8837. /**
  8838. * Regroup several parameters relative to the browser in use
  8839. */
  8840. var EngineCapabilities = /** @class */ (function () {
  8841. function EngineCapabilities() {
  8842. }
  8843. return EngineCapabilities;
  8844. }());
  8845. BABYLON.EngineCapabilities = EngineCapabilities;
  8846. /**
  8847. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8848. */
  8849. var Engine = /** @class */ (function () {
  8850. /**
  8851. * @constructor
  8852. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8853. * @param {boolean} [antialias] - enable antialias
  8854. * @param options - further options to be sent to the getContext function
  8855. */
  8856. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8857. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8858. var _this = this;
  8859. // Public members
  8860. this.forcePOTTextures = false;
  8861. this.isFullscreen = false;
  8862. this.isPointerLock = false;
  8863. this.cullBackFaces = true;
  8864. this.renderEvenInBackground = true;
  8865. this.preventCacheWipeBetweenFrames = false;
  8866. // To enable/disable IDB support and avoid XHR on .manifest
  8867. this.enableOfflineSupport = false;
  8868. this.scenes = new Array();
  8869. this.postProcesses = new Array();
  8870. // Observables
  8871. /**
  8872. * Observable event triggered each time the rendering canvas is resized
  8873. */
  8874. this.onResizeObservable = new BABYLON.Observable();
  8875. /**
  8876. * Observable event triggered each time the canvas loses focus
  8877. */
  8878. this.onCanvasBlurObservable = new BABYLON.Observable();
  8879. /**
  8880. * Observable event triggered each time the canvas gains focus
  8881. */
  8882. this.onCanvasFocusObservable = new BABYLON.Observable();
  8883. /**
  8884. * Observable event triggered each time the canvas receives pointerout event
  8885. */
  8886. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8887. /**
  8888. * Observable event triggered before each texture is initialized
  8889. */
  8890. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8891. //WebVR
  8892. this._vrDisplay = undefined;
  8893. this._vrSupported = false;
  8894. this._vrExclusivePointerMode = false;
  8895. // Uniform buffers list
  8896. this.disableUniformBuffers = false;
  8897. this._uniformBuffers = new Array();
  8898. // Observables
  8899. /**
  8900. * Observable raised when the engine begins a new frame
  8901. */
  8902. this.onBeginFrameObservable = new BABYLON.Observable();
  8903. /**
  8904. * Observable raised when the engine ends the current frame
  8905. */
  8906. this.onEndFrameObservable = new BABYLON.Observable();
  8907. /**
  8908. * Observable raised when the engine is about to compile a shader
  8909. */
  8910. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8911. /**
  8912. * Observable raised when the engine has jsut compiled a shader
  8913. */
  8914. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8915. this._windowIsBackground = false;
  8916. this._webGLVersion = 1.0;
  8917. this._badOS = false;
  8918. this._badDesktopOS = false;
  8919. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8920. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8921. this.onVRRequestPresentStart = new BABYLON.Observable();
  8922. this._colorWrite = true;
  8923. this._drawCalls = new BABYLON.PerfCounter();
  8924. this._textureCollisions = new BABYLON.PerfCounter();
  8925. this._renderingQueueLaunched = false;
  8926. this._activeRenderLoops = new Array();
  8927. // Deterministic lockstepMaxSteps
  8928. this._deterministicLockstep = false;
  8929. this._lockstepMaxSteps = 4;
  8930. // Lost context
  8931. this.onContextLostObservable = new BABYLON.Observable();
  8932. this.onContextRestoredObservable = new BABYLON.Observable();
  8933. this._contextWasLost = false;
  8934. this._doNotHandleContextLost = false;
  8935. // FPS
  8936. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8937. this._fps = 60;
  8938. this._deltaTime = 0;
  8939. /**
  8940. * Turn this value on if you want to pause FPS computation when in background
  8941. */
  8942. this.disablePerformanceMonitorInBackground = false;
  8943. // States
  8944. this._depthCullingState = new BABYLON._DepthCullingState();
  8945. this._stencilState = new BABYLON._StencilState();
  8946. this._alphaState = new BABYLON._AlphaState();
  8947. this._alphaMode = Engine.ALPHA_DISABLE;
  8948. // Cache
  8949. this._internalTexturesCache = new Array();
  8950. this._boundTexturesCache = {};
  8951. this._boundTexturesStack = new Array();
  8952. this._compiledEffects = {};
  8953. this._vertexAttribArraysEnabled = [];
  8954. this._uintIndicesCurrentlySet = false;
  8955. this._currentBoundBuffer = new Array();
  8956. this._currentBufferPointers = new Array();
  8957. this._currentInstanceLocations = new Array();
  8958. this._currentInstanceBuffers = new Array();
  8959. this._vaoRecordInProgress = false;
  8960. this._mustWipeVertexAttributes = false;
  8961. this._nextFreeTextureSlots = new Array();
  8962. this._activeRequests = new Array();
  8963. // Hardware supported Compressed Textures
  8964. this._texturesSupported = new Array();
  8965. this._onVRFullScreenTriggered = function () {
  8966. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8967. //get the old size before we change
  8968. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8969. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8970. //get the width and height, change the render size
  8971. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8972. _this.setHardwareScalingLevel(1);
  8973. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8974. }
  8975. else {
  8976. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8977. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8978. }
  8979. };
  8980. this._boundUniforms = {};
  8981. var canvas = null;
  8982. Engine.Instances.push(this);
  8983. if (!canvasOrContext) {
  8984. return;
  8985. }
  8986. options = options || {};
  8987. if (canvasOrContext.getContext) {
  8988. canvas = canvasOrContext;
  8989. this._renderingCanvas = canvas;
  8990. if (antialias != null) {
  8991. options.antialias = antialias;
  8992. }
  8993. if (options.deterministicLockstep === undefined) {
  8994. options.deterministicLockstep = false;
  8995. }
  8996. if (options.lockstepMaxSteps === undefined) {
  8997. options.lockstepMaxSteps = 4;
  8998. }
  8999. if (options.preserveDrawingBuffer === undefined) {
  9000. options.preserveDrawingBuffer = false;
  9001. }
  9002. if (options.audioEngine === undefined) {
  9003. options.audioEngine = true;
  9004. }
  9005. if (options.stencil === undefined) {
  9006. options.stencil = true;
  9007. }
  9008. this._deterministicLockstep = options.deterministicLockstep;
  9009. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9010. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9011. // Exceptions
  9012. if (navigator && navigator.userAgent) {
  9013. var ua = navigator.userAgent;
  9014. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9015. var exception = _a[_i];
  9016. var key = exception.key;
  9017. var targets = exception.targets;
  9018. if (ua.indexOf(key) > -1) {
  9019. if (exception.capture && exception.captureConstraint) {
  9020. var capture = exception.capture;
  9021. var constraint = exception.captureConstraint;
  9022. var regex = new RegExp(capture);
  9023. var matches = regex.exec(ua);
  9024. if (matches && matches.length > 0) {
  9025. var capturedValue = parseInt(matches[matches.length - 1]);
  9026. if (capturedValue >= constraint) {
  9027. continue;
  9028. }
  9029. }
  9030. }
  9031. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9032. var target = targets_1[_b];
  9033. switch (target) {
  9034. case "uniformBuffer":
  9035. this.disableUniformBuffers = true;
  9036. break;
  9037. }
  9038. }
  9039. break;
  9040. }
  9041. }
  9042. }
  9043. // GL
  9044. if (!options.disableWebGL2Support) {
  9045. try {
  9046. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9047. if (this._gl) {
  9048. this._webGLVersion = 2.0;
  9049. }
  9050. }
  9051. catch (e) {
  9052. // Do nothing
  9053. }
  9054. }
  9055. if (!this._gl) {
  9056. if (!canvas) {
  9057. throw new Error("The provided canvas is null or undefined.");
  9058. }
  9059. try {
  9060. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9061. }
  9062. catch (e) {
  9063. throw new Error("WebGL not supported");
  9064. }
  9065. }
  9066. if (!this._gl) {
  9067. throw new Error("WebGL not supported");
  9068. }
  9069. this._onCanvasFocus = function () {
  9070. _this.onCanvasFocusObservable.notifyObservers(_this);
  9071. };
  9072. this._onCanvasBlur = function () {
  9073. _this.onCanvasBlurObservable.notifyObservers(_this);
  9074. };
  9075. canvas.addEventListener("focus", this._onCanvasFocus);
  9076. canvas.addEventListener("blur", this._onCanvasBlur);
  9077. this._onBlur = function () {
  9078. if (_this.disablePerformanceMonitorInBackground) {
  9079. _this._performanceMonitor.disable();
  9080. }
  9081. _this._windowIsBackground = true;
  9082. };
  9083. this._onFocus = function () {
  9084. if (_this.disablePerformanceMonitorInBackground) {
  9085. _this._performanceMonitor.enable();
  9086. }
  9087. _this._windowIsBackground = false;
  9088. };
  9089. this._onCanvasPointerOut = function () {
  9090. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9091. };
  9092. window.addEventListener("blur", this._onBlur);
  9093. window.addEventListener("focus", this._onFocus);
  9094. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9095. // Context lost
  9096. if (!this._doNotHandleContextLost) {
  9097. this._onContextLost = function (evt) {
  9098. evt.preventDefault();
  9099. _this._contextWasLost = true;
  9100. BABYLON.Tools.Warn("WebGL context lost.");
  9101. _this.onContextLostObservable.notifyObservers(_this);
  9102. };
  9103. this._onContextRestored = function (evt) {
  9104. // Adding a timeout to avoid race condition at browser level
  9105. setTimeout(function () {
  9106. // Rebuild gl context
  9107. _this._initGLContext();
  9108. // Rebuild effects
  9109. _this._rebuildEffects();
  9110. // Rebuild textures
  9111. _this._rebuildInternalTextures();
  9112. // Rebuild buffers
  9113. _this._rebuildBuffers();
  9114. // Cache
  9115. _this.wipeCaches(true);
  9116. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9117. _this.onContextRestoredObservable.notifyObservers(_this);
  9118. _this._contextWasLost = false;
  9119. }, 0);
  9120. };
  9121. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9122. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9123. }
  9124. }
  9125. else {
  9126. this._gl = canvasOrContext;
  9127. this._renderingCanvas = this._gl.canvas;
  9128. if (this._gl.renderbufferStorageMultisample) {
  9129. this._webGLVersion = 2.0;
  9130. }
  9131. options.stencil = this._gl.getContextAttributes().stencil;
  9132. }
  9133. // Viewport
  9134. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9135. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9136. this.resize();
  9137. this._isStencilEnable = options.stencil ? true : false;
  9138. this._initGLContext();
  9139. if (canvas) {
  9140. // Fullscreen
  9141. this._onFullscreenChange = function () {
  9142. if (document.fullscreen !== undefined) {
  9143. _this.isFullscreen = document.fullscreen;
  9144. }
  9145. else if (document.mozFullScreen !== undefined) {
  9146. _this.isFullscreen = document.mozFullScreen;
  9147. }
  9148. else if (document.webkitIsFullScreen !== undefined) {
  9149. _this.isFullscreen = document.webkitIsFullScreen;
  9150. }
  9151. else if (document.msIsFullScreen !== undefined) {
  9152. _this.isFullscreen = document.msIsFullScreen;
  9153. }
  9154. // Pointer lock
  9155. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9156. canvas.requestPointerLock = canvas.requestPointerLock ||
  9157. canvas.msRequestPointerLock ||
  9158. canvas.mozRequestPointerLock ||
  9159. canvas.webkitRequestPointerLock;
  9160. if (canvas.requestPointerLock) {
  9161. canvas.requestPointerLock();
  9162. }
  9163. }
  9164. };
  9165. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9166. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9167. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9168. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9169. // Pointer lock
  9170. this._onPointerLockChange = function () {
  9171. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9172. document.webkitPointerLockElement === canvas ||
  9173. document.msPointerLockElement === canvas ||
  9174. document.pointerLockElement === canvas);
  9175. };
  9176. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9177. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9178. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9179. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9180. this._onVRDisplayPointerRestricted = function () {
  9181. if (canvas) {
  9182. canvas.requestPointerLock();
  9183. }
  9184. };
  9185. this._onVRDisplayPointerUnrestricted = function () {
  9186. document.exitPointerLock();
  9187. };
  9188. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9189. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9190. }
  9191. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9192. Engine.audioEngine = new BABYLON.AudioEngine();
  9193. }
  9194. // Prepare buffer pointers
  9195. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9196. this._currentBufferPointers[i] = new BufferPointer();
  9197. }
  9198. // Load WebVR Devices
  9199. if (options.autoEnableWebVR) {
  9200. this.initWebVR();
  9201. }
  9202. // Detect if we are running on a faulty buggy OS.
  9203. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9204. // Detect if we are running on a faulty buggy desktop OS.
  9205. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9206. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9207. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9208. }
  9209. Object.defineProperty(Engine, "LastCreatedEngine", {
  9210. get: function () {
  9211. if (Engine.Instances.length === 0) {
  9212. return null;
  9213. }
  9214. return Engine.Instances[Engine.Instances.length - 1];
  9215. },
  9216. enumerable: true,
  9217. configurable: true
  9218. });
  9219. Object.defineProperty(Engine, "LastCreatedScene", {
  9220. get: function () {
  9221. var lastCreatedEngine = Engine.LastCreatedEngine;
  9222. if (!lastCreatedEngine) {
  9223. return null;
  9224. }
  9225. if (lastCreatedEngine.scenes.length === 0) {
  9226. return null;
  9227. }
  9228. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9229. },
  9230. enumerable: true,
  9231. configurable: true
  9232. });
  9233. /**
  9234. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9235. */
  9236. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9237. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9238. var engine = Engine.Instances[engineIndex];
  9239. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9240. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9241. }
  9242. }
  9243. };
  9244. Object.defineProperty(Engine, "NEVER", {
  9245. get: function () {
  9246. return Engine._NEVER;
  9247. },
  9248. enumerable: true,
  9249. configurable: true
  9250. });
  9251. Object.defineProperty(Engine, "ALWAYS", {
  9252. get: function () {
  9253. return Engine._ALWAYS;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(Engine, "LESS", {
  9259. get: function () {
  9260. return Engine._LESS;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(Engine, "EQUAL", {
  9266. get: function () {
  9267. return Engine._EQUAL;
  9268. },
  9269. enumerable: true,
  9270. configurable: true
  9271. });
  9272. Object.defineProperty(Engine, "LEQUAL", {
  9273. get: function () {
  9274. return Engine._LEQUAL;
  9275. },
  9276. enumerable: true,
  9277. configurable: true
  9278. });
  9279. Object.defineProperty(Engine, "GREATER", {
  9280. get: function () {
  9281. return Engine._GREATER;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. Object.defineProperty(Engine, "GEQUAL", {
  9287. get: function () {
  9288. return Engine._GEQUAL;
  9289. },
  9290. enumerable: true,
  9291. configurable: true
  9292. });
  9293. Object.defineProperty(Engine, "NOTEQUAL", {
  9294. get: function () {
  9295. return Engine._NOTEQUAL;
  9296. },
  9297. enumerable: true,
  9298. configurable: true
  9299. });
  9300. Object.defineProperty(Engine, "KEEP", {
  9301. get: function () {
  9302. return Engine._KEEP;
  9303. },
  9304. enumerable: true,
  9305. configurable: true
  9306. });
  9307. Object.defineProperty(Engine, "REPLACE", {
  9308. get: function () {
  9309. return Engine._REPLACE;
  9310. },
  9311. enumerable: true,
  9312. configurable: true
  9313. });
  9314. Object.defineProperty(Engine, "INCR", {
  9315. get: function () {
  9316. return Engine._INCR;
  9317. },
  9318. enumerable: true,
  9319. configurable: true
  9320. });
  9321. Object.defineProperty(Engine, "DECR", {
  9322. get: function () {
  9323. return Engine._DECR;
  9324. },
  9325. enumerable: true,
  9326. configurable: true
  9327. });
  9328. Object.defineProperty(Engine, "INVERT", {
  9329. get: function () {
  9330. return Engine._INVERT;
  9331. },
  9332. enumerable: true,
  9333. configurable: true
  9334. });
  9335. Object.defineProperty(Engine, "INCR_WRAP", {
  9336. get: function () {
  9337. return Engine._INCR_WRAP;
  9338. },
  9339. enumerable: true,
  9340. configurable: true
  9341. });
  9342. Object.defineProperty(Engine, "DECR_WRAP", {
  9343. get: function () {
  9344. return Engine._DECR_WRAP;
  9345. },
  9346. enumerable: true,
  9347. configurable: true
  9348. });
  9349. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9350. get: function () {
  9351. return Engine._ALPHA_DISABLE;
  9352. },
  9353. enumerable: true,
  9354. configurable: true
  9355. });
  9356. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9357. get: function () {
  9358. return Engine._ALPHA_ONEONE;
  9359. },
  9360. enumerable: true,
  9361. configurable: true
  9362. });
  9363. Object.defineProperty(Engine, "ALPHA_ADD", {
  9364. get: function () {
  9365. return Engine._ALPHA_ADD;
  9366. },
  9367. enumerable: true,
  9368. configurable: true
  9369. });
  9370. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9371. get: function () {
  9372. return Engine._ALPHA_COMBINE;
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9378. get: function () {
  9379. return Engine._ALPHA_SUBTRACT;
  9380. },
  9381. enumerable: true,
  9382. configurable: true
  9383. });
  9384. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9385. get: function () {
  9386. return Engine._ALPHA_MULTIPLY;
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9392. get: function () {
  9393. return Engine._ALPHA_MAXIMIZED;
  9394. },
  9395. enumerable: true,
  9396. configurable: true
  9397. });
  9398. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9399. get: function () {
  9400. return Engine._ALPHA_PREMULTIPLIED;
  9401. },
  9402. enumerable: true,
  9403. configurable: true
  9404. });
  9405. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9406. get: function () {
  9407. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9408. },
  9409. enumerable: true,
  9410. configurable: true
  9411. });
  9412. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9413. get: function () {
  9414. return Engine._ALPHA_INTERPOLATE;
  9415. },
  9416. enumerable: true,
  9417. configurable: true
  9418. });
  9419. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9420. get: function () {
  9421. return Engine._ALPHA_SCREENMODE;
  9422. },
  9423. enumerable: true,
  9424. configurable: true
  9425. });
  9426. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9427. get: function () {
  9428. return Engine._DELAYLOADSTATE_NONE;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9434. get: function () {
  9435. return Engine._DELAYLOADSTATE_LOADED;
  9436. },
  9437. enumerable: true,
  9438. configurable: true
  9439. });
  9440. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9441. get: function () {
  9442. return Engine._DELAYLOADSTATE_LOADING;
  9443. },
  9444. enumerable: true,
  9445. configurable: true
  9446. });
  9447. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9448. get: function () {
  9449. return Engine._DELAYLOADSTATE_NOTLOADED;
  9450. },
  9451. enumerable: true,
  9452. configurable: true
  9453. });
  9454. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9455. get: function () {
  9456. return Engine._TEXTUREFORMAT_ALPHA;
  9457. },
  9458. enumerable: true,
  9459. configurable: true
  9460. });
  9461. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9462. get: function () {
  9463. return Engine._TEXTUREFORMAT_LUMINANCE;
  9464. },
  9465. enumerable: true,
  9466. configurable: true
  9467. });
  9468. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9469. get: function () {
  9470. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9471. },
  9472. enumerable: true,
  9473. configurable: true
  9474. });
  9475. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9476. get: function () {
  9477. return Engine._TEXTUREFORMAT_RGB;
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9483. get: function () {
  9484. return Engine._TEXTUREFORMAT_RGBA;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9490. get: function () {
  9491. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9492. },
  9493. enumerable: true,
  9494. configurable: true
  9495. });
  9496. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9497. get: function () {
  9498. return Engine._TEXTURETYPE_FLOAT;
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9504. get: function () {
  9505. return Engine._TEXTURETYPE_HALF_FLOAT;
  9506. },
  9507. enumerable: true,
  9508. configurable: true
  9509. });
  9510. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9511. get: function () {
  9512. return Engine._SCALEMODE_FLOOR;
  9513. },
  9514. enumerable: true,
  9515. configurable: true
  9516. });
  9517. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9518. get: function () {
  9519. return Engine._SCALEMODE_NEAREST;
  9520. },
  9521. enumerable: true,
  9522. configurable: true
  9523. });
  9524. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9525. get: function () {
  9526. return Engine._SCALEMODE_CEILING;
  9527. },
  9528. enumerable: true,
  9529. configurable: true
  9530. });
  9531. Object.defineProperty(Engine, "Version", {
  9532. get: function () {
  9533. return "3.2.0-alpha3";
  9534. },
  9535. enumerable: true,
  9536. configurable: true
  9537. });
  9538. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9539. get: function () {
  9540. return this._vrExclusivePointerMode;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9546. get: function () {
  9547. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9553. get: function () {
  9554. return this._webGLVersion < 2 || this.forcePOTTextures;
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. Object.defineProperty(Engine.prototype, "badOS", {
  9560. get: function () {
  9561. return this._badOS;
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9567. get: function () {
  9568. return this._badDesktopOS;
  9569. },
  9570. enumerable: true,
  9571. configurable: true
  9572. });
  9573. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9574. get: function () {
  9575. return this._performanceMonitor;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9581. get: function () {
  9582. return this._texturesSupported;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9588. get: function () {
  9589. return this._textureFormatInUse;
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(Engine.prototype, "currentViewport", {
  9595. get: function () {
  9596. return this._cachedViewport;
  9597. },
  9598. enumerable: true,
  9599. configurable: true
  9600. });
  9601. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9602. // Empty texture
  9603. get: function () {
  9604. if (!this._emptyTexture) {
  9605. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9606. }
  9607. return this._emptyTexture;
  9608. },
  9609. enumerable: true,
  9610. configurable: true
  9611. });
  9612. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9613. get: function () {
  9614. if (!this._emptyTexture3D) {
  9615. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9616. }
  9617. return this._emptyTexture3D;
  9618. },
  9619. enumerable: true,
  9620. configurable: true
  9621. });
  9622. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9623. get: function () {
  9624. if (!this._emptyCubeTexture) {
  9625. var faceData = new Uint8Array(4);
  9626. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9627. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9628. }
  9629. return this._emptyCubeTexture;
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Engine.prototype._rebuildInternalTextures = function () {
  9635. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9636. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9637. var internalTexture = currentState_1[_i];
  9638. internalTexture._rebuild();
  9639. }
  9640. };
  9641. Engine.prototype._rebuildEffects = function () {
  9642. for (var key in this._compiledEffects) {
  9643. var effect = this._compiledEffects[key];
  9644. effect._prepareEffect();
  9645. }
  9646. BABYLON.Effect.ResetCache();
  9647. };
  9648. Engine.prototype._rebuildBuffers = function () {
  9649. // Index / Vertex
  9650. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9651. var scene = _a[_i];
  9652. scene.resetCachedMaterial();
  9653. scene._rebuildGeometries();
  9654. scene._rebuildTextures();
  9655. }
  9656. // Uniforms
  9657. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9658. var uniformBuffer = _c[_b];
  9659. uniformBuffer._rebuild();
  9660. }
  9661. };
  9662. Engine.prototype._initGLContext = function () {
  9663. // Caps
  9664. this._caps = new EngineCapabilities();
  9665. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9666. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9667. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9668. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9669. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9670. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9671. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9672. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9673. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9674. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9675. // Infos
  9676. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9677. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9678. if (rendererInfo != null) {
  9679. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9680. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9681. }
  9682. if (!this._glVendor) {
  9683. this._glVendor = "Unknown vendor";
  9684. }
  9685. if (!this._glRenderer) {
  9686. this._glRenderer = "Unknown renderer";
  9687. }
  9688. // Constants
  9689. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9690. if (this._gl.RGBA16F !== 0x881A) {
  9691. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9692. }
  9693. if (this._gl.RGBA32F !== 0x8814) {
  9694. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9695. }
  9696. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9697. this._gl.DEPTH24_STENCIL8 = 35056;
  9698. }
  9699. // Extensions
  9700. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9701. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9702. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9703. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9704. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9705. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9706. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9707. 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');
  9708. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9709. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9710. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9711. this._caps.highPrecisionShaderSupported = true;
  9712. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9713. if (this._caps.timerQuery) {
  9714. if (this._webGLVersion === 1) {
  9715. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9716. }
  9717. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9718. }
  9719. // Checks if some of the format renders first to allow the use of webgl inspector.
  9720. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9721. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9722. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9723. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9724. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9725. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9726. if (this._webGLVersion > 1) {
  9727. this._gl.HALF_FLOAT_OES = 0x140B;
  9728. }
  9729. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9730. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9731. // Draw buffers
  9732. if (this._webGLVersion > 1) {
  9733. this._caps.drawBuffersExtension = true;
  9734. }
  9735. else {
  9736. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9737. if (drawBuffersExtension !== null) {
  9738. this._caps.drawBuffersExtension = true;
  9739. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9740. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9741. for (var i = 0; i < 16; i++) {
  9742. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9743. }
  9744. }
  9745. else {
  9746. this._caps.drawBuffersExtension = false;
  9747. }
  9748. }
  9749. // Depth Texture
  9750. if (this._webGLVersion > 1) {
  9751. this._caps.depthTextureExtension = true;
  9752. }
  9753. else {
  9754. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9755. if (depthTextureExtension != null) {
  9756. this._caps.depthTextureExtension = true;
  9757. }
  9758. }
  9759. // Vertex array object
  9760. if (this._webGLVersion > 1) {
  9761. this._caps.vertexArrayObject = true;
  9762. }
  9763. else {
  9764. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9765. if (vertexArrayObjectExtension != null) {
  9766. this._caps.vertexArrayObject = true;
  9767. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9768. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9769. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9770. }
  9771. else {
  9772. this._caps.vertexArrayObject = false;
  9773. }
  9774. }
  9775. // Instances count
  9776. if (this._webGLVersion > 1) {
  9777. this._caps.instancedArrays = true;
  9778. }
  9779. else {
  9780. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9781. if (instanceExtension != null) {
  9782. this._caps.instancedArrays = true;
  9783. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9784. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9785. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9786. }
  9787. else {
  9788. this._caps.instancedArrays = false;
  9789. }
  9790. }
  9791. // Intelligently add supported compressed formats in order to check for.
  9792. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9793. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9794. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9795. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9796. if (this._caps.astc)
  9797. this.texturesSupported.push('-astc.ktx');
  9798. if (this._caps.s3tc)
  9799. this.texturesSupported.push('-dxt.ktx');
  9800. if (this._caps.pvrtc)
  9801. this.texturesSupported.push('-pvrtc.ktx');
  9802. if (this._caps.etc2)
  9803. this.texturesSupported.push('-etc2.ktx');
  9804. if (this._caps.etc1)
  9805. this.texturesSupported.push('-etc1.ktx');
  9806. if (this._gl.getShaderPrecisionFormat) {
  9807. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9808. if (highp) {
  9809. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9810. }
  9811. }
  9812. // Depth buffer
  9813. this.setDepthBuffer(true);
  9814. this.setDepthFunctionToLessOrEqual();
  9815. this.setDepthWrite(true);
  9816. // Texture maps
  9817. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9818. this._nextFreeTextureSlots.push(slot);
  9819. }
  9820. };
  9821. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9822. get: function () {
  9823. return this._webGLVersion;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9829. /**
  9830. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9831. */
  9832. get: function () {
  9833. return this._isStencilEnable;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Engine.prototype._prepareWorkingCanvas = function () {
  9839. if (this._workingCanvas) {
  9840. return;
  9841. }
  9842. this._workingCanvas = document.createElement("canvas");
  9843. var context = this._workingCanvas.getContext("2d");
  9844. if (context) {
  9845. this._workingContext = context;
  9846. }
  9847. };
  9848. Engine.prototype.resetTextureCache = function () {
  9849. for (var key in this._boundTexturesCache) {
  9850. var boundTexture = this._boundTexturesCache[key];
  9851. if (boundTexture) {
  9852. this._removeDesignatedSlot(boundTexture);
  9853. }
  9854. this._boundTexturesCache[key] = null;
  9855. }
  9856. this._nextFreeTextureSlots = [];
  9857. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9858. this._nextFreeTextureSlots.push(slot);
  9859. }
  9860. this._activeChannel = -1;
  9861. };
  9862. Engine.prototype.isDeterministicLockStep = function () {
  9863. return this._deterministicLockstep;
  9864. };
  9865. Engine.prototype.getLockstepMaxSteps = function () {
  9866. return this._lockstepMaxSteps;
  9867. };
  9868. Engine.prototype.getGlInfo = function () {
  9869. return {
  9870. vendor: this._glVendor,
  9871. renderer: this._glRenderer,
  9872. version: this._glVersion
  9873. };
  9874. };
  9875. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9876. if (useScreen === void 0) { useScreen = false; }
  9877. var viewport = camera.viewport;
  9878. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9879. };
  9880. Engine.prototype.getRenderWidth = function (useScreen) {
  9881. if (useScreen === void 0) { useScreen = false; }
  9882. if (!useScreen && this._currentRenderTarget) {
  9883. return this._currentRenderTarget.width;
  9884. }
  9885. return this._gl.drawingBufferWidth;
  9886. };
  9887. Engine.prototype.getRenderHeight = function (useScreen) {
  9888. if (useScreen === void 0) { useScreen = false; }
  9889. if (!useScreen && this._currentRenderTarget) {
  9890. return this._currentRenderTarget.height;
  9891. }
  9892. return this._gl.drawingBufferHeight;
  9893. };
  9894. Engine.prototype.getRenderingCanvas = function () {
  9895. return this._renderingCanvas;
  9896. };
  9897. Engine.prototype.getRenderingCanvasClientRect = function () {
  9898. if (!this._renderingCanvas) {
  9899. return null;
  9900. }
  9901. return this._renderingCanvas.getBoundingClientRect();
  9902. };
  9903. Engine.prototype.setHardwareScalingLevel = function (level) {
  9904. this._hardwareScalingLevel = level;
  9905. this.resize();
  9906. };
  9907. Engine.prototype.getHardwareScalingLevel = function () {
  9908. return this._hardwareScalingLevel;
  9909. };
  9910. Engine.prototype.getLoadedTexturesCache = function () {
  9911. return this._internalTexturesCache;
  9912. };
  9913. Engine.prototype.getCaps = function () {
  9914. return this._caps;
  9915. };
  9916. Object.defineProperty(Engine.prototype, "drawCalls", {
  9917. /** The number of draw calls submitted last frame */
  9918. get: function () {
  9919. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9920. return 0;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9926. get: function () {
  9927. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9928. return null;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Engine.prototype.getDepthFunction = function () {
  9934. return this._depthCullingState.depthFunc;
  9935. };
  9936. Engine.prototype.setDepthFunction = function (depthFunc) {
  9937. this._depthCullingState.depthFunc = depthFunc;
  9938. };
  9939. Engine.prototype.setDepthFunctionToGreater = function () {
  9940. this._depthCullingState.depthFunc = this._gl.GREATER;
  9941. };
  9942. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9943. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9944. };
  9945. Engine.prototype.setDepthFunctionToLess = function () {
  9946. this._depthCullingState.depthFunc = this._gl.LESS;
  9947. };
  9948. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9949. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9950. };
  9951. Engine.prototype.getStencilBuffer = function () {
  9952. return this._stencilState.stencilTest;
  9953. };
  9954. Engine.prototype.setStencilBuffer = function (enable) {
  9955. this._stencilState.stencilTest = enable;
  9956. };
  9957. Engine.prototype.getStencilMask = function () {
  9958. return this._stencilState.stencilMask;
  9959. };
  9960. Engine.prototype.setStencilMask = function (mask) {
  9961. this._stencilState.stencilMask = mask;
  9962. };
  9963. Engine.prototype.getStencilFunction = function () {
  9964. return this._stencilState.stencilFunc;
  9965. };
  9966. Engine.prototype.getStencilFunctionReference = function () {
  9967. return this._stencilState.stencilFuncRef;
  9968. };
  9969. Engine.prototype.getStencilFunctionMask = function () {
  9970. return this._stencilState.stencilFuncMask;
  9971. };
  9972. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9973. this._stencilState.stencilFunc = stencilFunc;
  9974. };
  9975. Engine.prototype.setStencilFunctionReference = function (reference) {
  9976. this._stencilState.stencilFuncRef = reference;
  9977. };
  9978. Engine.prototype.setStencilFunctionMask = function (mask) {
  9979. this._stencilState.stencilFuncMask = mask;
  9980. };
  9981. Engine.prototype.getStencilOperationFail = function () {
  9982. return this._stencilState.stencilOpStencilFail;
  9983. };
  9984. Engine.prototype.getStencilOperationDepthFail = function () {
  9985. return this._stencilState.stencilOpDepthFail;
  9986. };
  9987. Engine.prototype.getStencilOperationPass = function () {
  9988. return this._stencilState.stencilOpStencilDepthPass;
  9989. };
  9990. Engine.prototype.setStencilOperationFail = function (operation) {
  9991. this._stencilState.stencilOpStencilFail = operation;
  9992. };
  9993. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9994. this._stencilState.stencilOpDepthFail = operation;
  9995. };
  9996. Engine.prototype.setStencilOperationPass = function (operation) {
  9997. this._stencilState.stencilOpStencilDepthPass = operation;
  9998. };
  9999. Engine.prototype.setDitheringState = function (value) {
  10000. if (value) {
  10001. this._gl.enable(this._gl.DITHER);
  10002. }
  10003. else {
  10004. this._gl.disable(this._gl.DITHER);
  10005. }
  10006. };
  10007. Engine.prototype.setRasterizerState = function (value) {
  10008. if (value) {
  10009. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10010. }
  10011. else {
  10012. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10013. }
  10014. };
  10015. /**
  10016. * stop executing a render loop function and remove it from the execution array
  10017. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10018. */
  10019. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10020. if (!renderFunction) {
  10021. this._activeRenderLoops = [];
  10022. return;
  10023. }
  10024. var index = this._activeRenderLoops.indexOf(renderFunction);
  10025. if (index >= 0) {
  10026. this._activeRenderLoops.splice(index, 1);
  10027. }
  10028. };
  10029. Engine.prototype._renderLoop = function () {
  10030. if (!this._contextWasLost) {
  10031. var shouldRender = true;
  10032. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10033. shouldRender = false;
  10034. }
  10035. if (shouldRender) {
  10036. // Start new frame
  10037. this.beginFrame();
  10038. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10039. var renderFunction = this._activeRenderLoops[index];
  10040. renderFunction();
  10041. }
  10042. // Present
  10043. this.endFrame();
  10044. }
  10045. }
  10046. if (this._activeRenderLoops.length > 0) {
  10047. // Register new frame
  10048. var requester = null;
  10049. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10050. requester = this._vrDisplay;
  10051. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10052. }
  10053. else {
  10054. this._renderingQueueLaunched = false;
  10055. }
  10056. };
  10057. /**
  10058. * Register and execute a render loop. The engine can have more than one render function.
  10059. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10060. * @example
  10061. * engine.runRenderLoop(function () {
  10062. * scene.render()
  10063. * })
  10064. */
  10065. Engine.prototype.runRenderLoop = function (renderFunction) {
  10066. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10067. return;
  10068. }
  10069. this._activeRenderLoops.push(renderFunction);
  10070. if (!this._renderingQueueLaunched) {
  10071. this._renderingQueueLaunched = true;
  10072. this._bindedRenderFunction = this._renderLoop.bind(this);
  10073. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10074. }
  10075. };
  10076. /**
  10077. * Toggle full screen mode.
  10078. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10079. * @param {any} options - an options object to be sent to the requestFullscreen function
  10080. */
  10081. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10082. if (this.isFullscreen) {
  10083. BABYLON.Tools.ExitFullscreen();
  10084. }
  10085. else {
  10086. this._pointerLockRequested = requestPointerLock;
  10087. if (this._renderingCanvas) {
  10088. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10089. }
  10090. }
  10091. };
  10092. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10093. if (stencil === void 0) { stencil = false; }
  10094. this.applyStates();
  10095. var mode = 0;
  10096. if (backBuffer && color) {
  10097. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10098. mode |= this._gl.COLOR_BUFFER_BIT;
  10099. }
  10100. if (depth) {
  10101. this._gl.clearDepth(1.0);
  10102. mode |= this._gl.DEPTH_BUFFER_BIT;
  10103. }
  10104. if (stencil) {
  10105. this._gl.clearStencil(0);
  10106. mode |= this._gl.STENCIL_BUFFER_BIT;
  10107. }
  10108. this._gl.clear(mode);
  10109. };
  10110. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10111. var gl = this._gl;
  10112. // Save state
  10113. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10114. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10115. // Change state
  10116. gl.enable(gl.SCISSOR_TEST);
  10117. gl.scissor(x, y, width, height);
  10118. // Clear
  10119. this.clear(clearColor, true, true, true);
  10120. // Restore state
  10121. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10122. if (curScissor === true) {
  10123. gl.enable(gl.SCISSOR_TEST);
  10124. }
  10125. else {
  10126. gl.disable(gl.SCISSOR_TEST);
  10127. }
  10128. };
  10129. /**
  10130. * Set the WebGL's viewport
  10131. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10132. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10133. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10134. */
  10135. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10136. var width = requiredWidth || this.getRenderWidth();
  10137. var height = requiredHeight || this.getRenderHeight();
  10138. var x = viewport.x || 0;
  10139. var y = viewport.y || 0;
  10140. this._cachedViewport = viewport;
  10141. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10142. };
  10143. /**
  10144. * Directly set the WebGL Viewport
  10145. * The x, y, width & height are directly passed to the WebGL call
  10146. * @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.
  10147. */
  10148. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10149. var currentViewport = this._cachedViewport;
  10150. this._cachedViewport = null;
  10151. this._gl.viewport(x, y, width, height);
  10152. return currentViewport;
  10153. };
  10154. Engine.prototype.beginFrame = function () {
  10155. this.onBeginFrameObservable.notifyObservers(this);
  10156. this._measureFps();
  10157. };
  10158. Engine.prototype.endFrame = function () {
  10159. //force a flush in case we are using a bad OS.
  10160. if (this._badOS) {
  10161. this.flushFramebuffer();
  10162. }
  10163. //submit frame to the vr device, if enabled
  10164. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10165. // TODO: We should only submit the frame if we read frameData successfully.
  10166. this._vrDisplay.submitFrame();
  10167. }
  10168. this.onEndFrameObservable.notifyObservers(this);
  10169. };
  10170. /**
  10171. * resize the view according to the canvas' size.
  10172. * @example
  10173. * window.addEventListener("resize", function () {
  10174. * engine.resize();
  10175. * });
  10176. */
  10177. Engine.prototype.resize = function () {
  10178. // We're not resizing the size of the canvas while in VR mode & presenting
  10179. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10180. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10181. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10182. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10183. }
  10184. };
  10185. /**
  10186. * force a specific size of the canvas
  10187. * @param {number} width - the new canvas' width
  10188. * @param {number} height - the new canvas' height
  10189. */
  10190. Engine.prototype.setSize = function (width, height) {
  10191. if (!this._renderingCanvas) {
  10192. return;
  10193. }
  10194. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10195. return;
  10196. }
  10197. this._renderingCanvas.width = width;
  10198. this._renderingCanvas.height = height;
  10199. for (var index = 0; index < this.scenes.length; index++) {
  10200. var scene = this.scenes[index];
  10201. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10202. var cam = scene.cameras[camIndex];
  10203. cam._currentRenderId = 0;
  10204. }
  10205. }
  10206. if (this.onResizeObservable.hasObservers) {
  10207. this.onResizeObservable.notifyObservers(this);
  10208. }
  10209. };
  10210. // WebVR functions
  10211. Engine.prototype.isVRDevicePresent = function () {
  10212. return !!this._vrDisplay;
  10213. };
  10214. Engine.prototype.getVRDevice = function () {
  10215. return this._vrDisplay;
  10216. };
  10217. Engine.prototype.initWebVR = function () {
  10218. var _this = this;
  10219. var notifyObservers = function () {
  10220. var eventArgs = {
  10221. vrDisplay: _this._vrDisplay,
  10222. vrSupported: _this._vrSupported
  10223. };
  10224. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10225. };
  10226. if (!this._onVrDisplayConnect) {
  10227. this._onVrDisplayConnect = function (event) {
  10228. _this._vrDisplay = event.display;
  10229. notifyObservers();
  10230. };
  10231. this._onVrDisplayDisconnect = function () {
  10232. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10233. _this._vrDisplay = undefined;
  10234. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10235. notifyObservers();
  10236. };
  10237. this._onVrDisplayPresentChange = function () {
  10238. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10239. };
  10240. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10241. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10242. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10243. }
  10244. this._getVRDisplays(notifyObservers);
  10245. return this.onVRDisplayChangedObservable;
  10246. };
  10247. Engine.prototype.enableVR = function () {
  10248. var _this = this;
  10249. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10250. var onResolved = function () {
  10251. _this.onVRRequestPresentComplete.notifyObservers(true);
  10252. _this._onVRFullScreenTriggered();
  10253. };
  10254. var onRejected = function () {
  10255. _this.onVRRequestPresentComplete.notifyObservers(false);
  10256. };
  10257. this.onVRRequestPresentStart.notifyObservers(this);
  10258. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10259. }
  10260. };
  10261. Engine.prototype.disableVR = function () {
  10262. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10263. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10264. }
  10265. };
  10266. Engine.prototype._getVRDisplays = function (callback) {
  10267. var _this = this;
  10268. var getWebVRDevices = function (devices) {
  10269. _this._vrSupported = true;
  10270. // note that devices may actually be an empty array. This is fine;
  10271. // we expect this._vrDisplay to be undefined in this case.
  10272. return _this._vrDisplay = devices[0];
  10273. };
  10274. if (navigator.getVRDisplays) {
  10275. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10276. // TODO: System CANNOT support WebVR, despite API presence.
  10277. _this._vrSupported = false;
  10278. callback();
  10279. });
  10280. }
  10281. else {
  10282. // TODO: Browser does not support WebVR
  10283. this._vrDisplay = undefined;
  10284. this._vrSupported = false;
  10285. callback();
  10286. }
  10287. };
  10288. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10289. if (this._currentRenderTarget) {
  10290. this.unBindFramebuffer(this._currentRenderTarget);
  10291. }
  10292. this._currentRenderTarget = texture;
  10293. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10294. var gl = this._gl;
  10295. if (texture.isCube) {
  10296. if (faceIndex === undefined) {
  10297. faceIndex = 0;
  10298. }
  10299. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10300. }
  10301. if (this._cachedViewport && !forceFullscreenViewport) {
  10302. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10303. }
  10304. else {
  10305. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10306. }
  10307. this.wipeCaches();
  10308. };
  10309. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10310. if (this._currentFramebuffer !== framebuffer) {
  10311. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10312. this._currentFramebuffer = framebuffer;
  10313. }
  10314. };
  10315. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10316. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10317. this._currentRenderTarget = null;
  10318. // If MSAA, we need to bitblt back to main texture
  10319. var gl = this._gl;
  10320. if (texture._MSAAFramebuffer) {
  10321. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10322. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10323. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10324. }
  10325. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10326. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10327. gl.generateMipmap(gl.TEXTURE_2D);
  10328. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10329. }
  10330. if (onBeforeUnbind) {
  10331. if (texture._MSAAFramebuffer) {
  10332. // Bind the correct framebuffer
  10333. this.bindUnboundFramebuffer(texture._framebuffer);
  10334. }
  10335. onBeforeUnbind();
  10336. }
  10337. this.bindUnboundFramebuffer(null);
  10338. };
  10339. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10340. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10341. this._currentRenderTarget = null;
  10342. // If MSAA, we need to bitblt back to main texture
  10343. var gl = this._gl;
  10344. if (textures[0]._MSAAFramebuffer) {
  10345. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10346. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10347. var attachments = textures[0]._attachments;
  10348. if (!attachments) {
  10349. attachments = new Array(textures.length);
  10350. textures[0]._attachments = attachments;
  10351. }
  10352. for (var i = 0; i < textures.length; i++) {
  10353. var texture = textures[i];
  10354. for (var j = 0; j < attachments.length; j++) {
  10355. attachments[j] = gl.NONE;
  10356. }
  10357. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10358. gl.readBuffer(attachments[i]);
  10359. gl.drawBuffers(attachments);
  10360. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10361. }
  10362. for (var i = 0; i < attachments.length; i++) {
  10363. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10364. }
  10365. gl.drawBuffers(attachments);
  10366. }
  10367. for (var i = 0; i < textures.length; i++) {
  10368. var texture = textures[i];
  10369. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10370. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10371. gl.generateMipmap(gl.TEXTURE_2D);
  10372. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10373. }
  10374. }
  10375. if (onBeforeUnbind) {
  10376. if (textures[0]._MSAAFramebuffer) {
  10377. // Bind the correct framebuffer
  10378. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10379. }
  10380. onBeforeUnbind();
  10381. }
  10382. this.bindUnboundFramebuffer(null);
  10383. };
  10384. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10385. if (texture.generateMipMaps) {
  10386. var gl = this._gl;
  10387. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10388. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10390. }
  10391. };
  10392. Engine.prototype.flushFramebuffer = function () {
  10393. this._gl.flush();
  10394. };
  10395. Engine.prototype.restoreDefaultFramebuffer = function () {
  10396. if (this._currentRenderTarget) {
  10397. this.unBindFramebuffer(this._currentRenderTarget);
  10398. }
  10399. else {
  10400. this.bindUnboundFramebuffer(null);
  10401. }
  10402. if (this._cachedViewport) {
  10403. this.setViewport(this._cachedViewport);
  10404. }
  10405. this.wipeCaches();
  10406. };
  10407. // UBOs
  10408. Engine.prototype.createUniformBuffer = function (elements) {
  10409. var ubo = this._gl.createBuffer();
  10410. if (!ubo) {
  10411. throw new Error("Unable to create uniform buffer");
  10412. }
  10413. this.bindUniformBuffer(ubo);
  10414. if (elements instanceof Float32Array) {
  10415. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10416. }
  10417. else {
  10418. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10419. }
  10420. this.bindUniformBuffer(null);
  10421. ubo.references = 1;
  10422. return ubo;
  10423. };
  10424. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10425. var ubo = this._gl.createBuffer();
  10426. if (!ubo) {
  10427. throw new Error("Unable to create dynamic uniform buffer");
  10428. }
  10429. this.bindUniformBuffer(ubo);
  10430. if (elements instanceof Float32Array) {
  10431. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10432. }
  10433. else {
  10434. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10435. }
  10436. this.bindUniformBuffer(null);
  10437. ubo.references = 1;
  10438. return ubo;
  10439. };
  10440. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10441. this.bindUniformBuffer(uniformBuffer);
  10442. if (offset === undefined) {
  10443. offset = 0;
  10444. }
  10445. if (count === undefined) {
  10446. if (elements instanceof Float32Array) {
  10447. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10448. }
  10449. else {
  10450. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10451. }
  10452. }
  10453. else {
  10454. if (elements instanceof Float32Array) {
  10455. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10456. }
  10457. else {
  10458. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10459. }
  10460. }
  10461. this.bindUniformBuffer(null);
  10462. };
  10463. // VBOs
  10464. Engine.prototype._resetVertexBufferBinding = function () {
  10465. this.bindArrayBuffer(null);
  10466. this._cachedVertexBuffers = null;
  10467. };
  10468. Engine.prototype.createVertexBuffer = function (vertices) {
  10469. var vbo = this._gl.createBuffer();
  10470. if (!vbo) {
  10471. throw new Error("Unable to create vertex buffer");
  10472. }
  10473. this.bindArrayBuffer(vbo);
  10474. if (vertices instanceof Float32Array) {
  10475. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10476. }
  10477. else {
  10478. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10479. }
  10480. this._resetVertexBufferBinding();
  10481. vbo.references = 1;
  10482. return vbo;
  10483. };
  10484. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10485. var vbo = this._gl.createBuffer();
  10486. if (!vbo) {
  10487. throw new Error("Unable to create dynamic vertex buffer");
  10488. }
  10489. this.bindArrayBuffer(vbo);
  10490. if (vertices instanceof Float32Array) {
  10491. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10492. }
  10493. else {
  10494. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10495. }
  10496. this._resetVertexBufferBinding();
  10497. vbo.references = 1;
  10498. return vbo;
  10499. };
  10500. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10501. if (offset === void 0) { offset = 0; }
  10502. // Force cache update
  10503. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10504. this.bindIndexBuffer(indexBuffer);
  10505. var arrayBuffer;
  10506. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10507. arrayBuffer = indices;
  10508. }
  10509. else {
  10510. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10511. }
  10512. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10513. this._resetIndexBufferBinding();
  10514. };
  10515. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10516. this.bindArrayBuffer(vertexBuffer);
  10517. if (offset === undefined) {
  10518. offset = 0;
  10519. }
  10520. if (count === undefined) {
  10521. if (vertices instanceof Float32Array) {
  10522. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10523. }
  10524. else {
  10525. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10526. }
  10527. }
  10528. else {
  10529. if (vertices instanceof Float32Array) {
  10530. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10531. }
  10532. else {
  10533. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10534. }
  10535. }
  10536. this._resetVertexBufferBinding();
  10537. };
  10538. Engine.prototype._resetIndexBufferBinding = function () {
  10539. this.bindIndexBuffer(null);
  10540. this._cachedIndexBuffer = null;
  10541. };
  10542. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10543. var vbo = this._gl.createBuffer();
  10544. if (!vbo) {
  10545. throw new Error("Unable to create index buffer");
  10546. }
  10547. this.bindIndexBuffer(vbo);
  10548. // Check for 32 bits indices
  10549. var arrayBuffer;
  10550. var need32Bits = false;
  10551. if (indices instanceof Uint16Array) {
  10552. arrayBuffer = indices;
  10553. }
  10554. else {
  10555. //check 32 bit support
  10556. if (this._caps.uintIndices) {
  10557. if (indices instanceof Uint32Array) {
  10558. arrayBuffer = indices;
  10559. need32Bits = true;
  10560. }
  10561. else {
  10562. //number[] or Int32Array, check if 32 bit is necessary
  10563. for (var index = 0; index < indices.length; index++) {
  10564. if (indices[index] > 65535) {
  10565. need32Bits = true;
  10566. break;
  10567. }
  10568. }
  10569. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10570. }
  10571. }
  10572. else {
  10573. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10574. arrayBuffer = new Uint16Array(indices);
  10575. }
  10576. }
  10577. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10578. this._resetIndexBufferBinding();
  10579. vbo.references = 1;
  10580. vbo.is32Bits = need32Bits;
  10581. return vbo;
  10582. };
  10583. Engine.prototype.bindArrayBuffer = function (buffer) {
  10584. if (!this._vaoRecordInProgress) {
  10585. this._unbindVertexArrayObject();
  10586. }
  10587. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10588. };
  10589. Engine.prototype.bindUniformBuffer = function (buffer) {
  10590. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10591. };
  10592. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10593. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10594. };
  10595. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10596. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10597. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10598. };
  10599. ;
  10600. Engine.prototype.bindIndexBuffer = function (buffer) {
  10601. if (!this._vaoRecordInProgress) {
  10602. this._unbindVertexArrayObject();
  10603. }
  10604. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10605. };
  10606. Engine.prototype.bindBuffer = function (buffer, target) {
  10607. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10608. this._gl.bindBuffer(target, buffer);
  10609. this._currentBoundBuffer[target] = buffer;
  10610. }
  10611. };
  10612. Engine.prototype.updateArrayBuffer = function (data) {
  10613. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10614. };
  10615. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10616. var pointer = this._currentBufferPointers[indx];
  10617. var changed = false;
  10618. if (!pointer.active) {
  10619. changed = true;
  10620. pointer.active = true;
  10621. pointer.index = indx;
  10622. pointer.size = size;
  10623. pointer.type = type;
  10624. pointer.normalized = normalized;
  10625. pointer.stride = stride;
  10626. pointer.offset = offset;
  10627. pointer.buffer = buffer;
  10628. }
  10629. else {
  10630. if (pointer.buffer !== buffer) {
  10631. pointer.buffer = buffer;
  10632. changed = true;
  10633. }
  10634. if (pointer.size !== size) {
  10635. pointer.size = size;
  10636. changed = true;
  10637. }
  10638. if (pointer.type !== type) {
  10639. pointer.type = type;
  10640. changed = true;
  10641. }
  10642. if (pointer.normalized !== normalized) {
  10643. pointer.normalized = normalized;
  10644. changed = true;
  10645. }
  10646. if (pointer.stride !== stride) {
  10647. pointer.stride = stride;
  10648. changed = true;
  10649. }
  10650. if (pointer.offset !== offset) {
  10651. pointer.offset = offset;
  10652. changed = true;
  10653. }
  10654. }
  10655. if (changed || this._vaoRecordInProgress) {
  10656. this.bindArrayBuffer(buffer);
  10657. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10658. }
  10659. };
  10660. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10661. if (indexBuffer == null) {
  10662. return;
  10663. }
  10664. if (this._cachedIndexBuffer !== indexBuffer) {
  10665. this._cachedIndexBuffer = indexBuffer;
  10666. this.bindIndexBuffer(indexBuffer);
  10667. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10668. }
  10669. };
  10670. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10671. var attributes = effect.getAttributesNames();
  10672. if (!this._vaoRecordInProgress) {
  10673. this._unbindVertexArrayObject();
  10674. }
  10675. this.unbindAllAttributes();
  10676. for (var index = 0; index < attributes.length; index++) {
  10677. var order = effect.getAttributeLocation(index);
  10678. if (order >= 0) {
  10679. var vertexBuffer = vertexBuffers[attributes[index]];
  10680. if (!vertexBuffer) {
  10681. continue;
  10682. }
  10683. this._gl.enableVertexAttribArray(order);
  10684. if (!this._vaoRecordInProgress) {
  10685. this._vertexAttribArraysEnabled[order] = true;
  10686. }
  10687. var buffer = vertexBuffer.getBuffer();
  10688. if (buffer) {
  10689. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10690. if (vertexBuffer.getIsInstanced()) {
  10691. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10692. if (!this._vaoRecordInProgress) {
  10693. this._currentInstanceLocations.push(order);
  10694. this._currentInstanceBuffers.push(buffer);
  10695. }
  10696. }
  10697. }
  10698. }
  10699. }
  10700. };
  10701. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10702. var vao = this._gl.createVertexArray();
  10703. this._vaoRecordInProgress = true;
  10704. this._gl.bindVertexArray(vao);
  10705. this._mustWipeVertexAttributes = true;
  10706. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10707. this.bindIndexBuffer(indexBuffer);
  10708. this._vaoRecordInProgress = false;
  10709. this._gl.bindVertexArray(null);
  10710. return vao;
  10711. };
  10712. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10713. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10714. this._cachedVertexArrayObject = vertexArrayObject;
  10715. this._gl.bindVertexArray(vertexArrayObject);
  10716. this._cachedVertexBuffers = null;
  10717. this._cachedIndexBuffer = null;
  10718. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10719. this._mustWipeVertexAttributes = true;
  10720. }
  10721. };
  10722. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10723. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10724. this._cachedVertexBuffers = vertexBuffer;
  10725. this._cachedEffectForVertexBuffers = effect;
  10726. var attributesCount = effect.getAttributesCount();
  10727. this._unbindVertexArrayObject();
  10728. this.unbindAllAttributes();
  10729. var offset = 0;
  10730. for (var index = 0; index < attributesCount; index++) {
  10731. if (index < vertexDeclaration.length) {
  10732. var order = effect.getAttributeLocation(index);
  10733. if (order >= 0) {
  10734. this._gl.enableVertexAttribArray(order);
  10735. this._vertexAttribArraysEnabled[order] = true;
  10736. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10737. }
  10738. offset += vertexDeclaration[index] * 4;
  10739. }
  10740. }
  10741. }
  10742. this._bindIndexBufferWithCache(indexBuffer);
  10743. };
  10744. Engine.prototype._unbindVertexArrayObject = function () {
  10745. if (!this._cachedVertexArrayObject) {
  10746. return;
  10747. }
  10748. this._cachedVertexArrayObject = null;
  10749. this._gl.bindVertexArray(null);
  10750. };
  10751. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10752. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10753. this._cachedVertexBuffers = vertexBuffers;
  10754. this._cachedEffectForVertexBuffers = effect;
  10755. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10756. }
  10757. this._bindIndexBufferWithCache(indexBuffer);
  10758. };
  10759. Engine.prototype.unbindInstanceAttributes = function () {
  10760. var boundBuffer;
  10761. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10762. var instancesBuffer = this._currentInstanceBuffers[i];
  10763. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10764. boundBuffer = instancesBuffer;
  10765. this.bindArrayBuffer(instancesBuffer);
  10766. }
  10767. var offsetLocation = this._currentInstanceLocations[i];
  10768. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10769. }
  10770. this._currentInstanceBuffers.length = 0;
  10771. this._currentInstanceLocations.length = 0;
  10772. };
  10773. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10774. this._gl.deleteVertexArray(vao);
  10775. };
  10776. Engine.prototype._releaseBuffer = function (buffer) {
  10777. buffer.references--;
  10778. if (buffer.references === 0) {
  10779. this._gl.deleteBuffer(buffer);
  10780. return true;
  10781. }
  10782. return false;
  10783. };
  10784. Engine.prototype.createInstancesBuffer = function (capacity) {
  10785. var buffer = this._gl.createBuffer();
  10786. if (!buffer) {
  10787. throw new Error("Unable to create instance buffer");
  10788. }
  10789. buffer.capacity = capacity;
  10790. this.bindArrayBuffer(buffer);
  10791. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10792. return buffer;
  10793. };
  10794. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10795. this._gl.deleteBuffer(buffer);
  10796. };
  10797. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10798. this.bindArrayBuffer(instancesBuffer);
  10799. if (data) {
  10800. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10801. }
  10802. if (offsetLocations[0].index !== undefined) {
  10803. var stride = 0;
  10804. for (var i = 0; i < offsetLocations.length; i++) {
  10805. var ai = offsetLocations[i];
  10806. stride += ai.attributeSize * 4;
  10807. }
  10808. for (var i = 0; i < offsetLocations.length; i++) {
  10809. var ai = offsetLocations[i];
  10810. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10811. this._gl.enableVertexAttribArray(ai.index);
  10812. this._vertexAttribArraysEnabled[ai.index] = true;
  10813. }
  10814. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10815. this._gl.vertexAttribDivisor(ai.index, 1);
  10816. this._currentInstanceLocations.push(ai.index);
  10817. this._currentInstanceBuffers.push(instancesBuffer);
  10818. }
  10819. }
  10820. else {
  10821. for (var index = 0; index < 4; index++) {
  10822. var offsetLocation = offsetLocations[index];
  10823. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10824. this._gl.enableVertexAttribArray(offsetLocation);
  10825. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10826. }
  10827. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10828. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10829. this._currentInstanceLocations.push(offsetLocation);
  10830. this._currentInstanceBuffers.push(instancesBuffer);
  10831. }
  10832. }
  10833. };
  10834. Engine.prototype.applyStates = function () {
  10835. this._depthCullingState.apply(this._gl);
  10836. this._stencilState.apply(this._gl);
  10837. this._alphaState.apply(this._gl);
  10838. };
  10839. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10840. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10841. };
  10842. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10843. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10844. };
  10845. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10846. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10847. };
  10848. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10849. // Apply states
  10850. this.applyStates();
  10851. this._drawCalls.addCount(1, false);
  10852. // Render
  10853. var drawMode = this.DrawMode(fillMode);
  10854. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10855. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10856. if (instancesCount) {
  10857. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10858. }
  10859. else {
  10860. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10861. }
  10862. };
  10863. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10864. // Apply states
  10865. this.applyStates();
  10866. this._drawCalls.addCount(1, false);
  10867. var drawMode = this.DrawMode(fillMode);
  10868. if (instancesCount) {
  10869. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10870. }
  10871. else {
  10872. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10873. }
  10874. };
  10875. Engine.prototype.DrawMode = function (fillMode) {
  10876. switch (fillMode) {
  10877. // Triangle views
  10878. case BABYLON.Material.TriangleFillMode:
  10879. return this._gl.TRIANGLES;
  10880. case BABYLON.Material.PointFillMode:
  10881. return this._gl.POINTS;
  10882. case BABYLON.Material.WireFrameFillMode:
  10883. return this._gl.LINES;
  10884. // Draw modes
  10885. case BABYLON.Material.PointListDrawMode:
  10886. return this._gl.POINTS;
  10887. case BABYLON.Material.LineListDrawMode:
  10888. return this._gl.LINES;
  10889. case BABYLON.Material.LineLoopDrawMode:
  10890. return this._gl.LINE_LOOP;
  10891. case BABYLON.Material.LineStripDrawMode:
  10892. return this._gl.LINE_STRIP;
  10893. case BABYLON.Material.TriangleStripDrawMode:
  10894. return this._gl.TRIANGLE_STRIP;
  10895. case BABYLON.Material.TriangleFanDrawMode:
  10896. return this._gl.TRIANGLE_FAN;
  10897. default:
  10898. return this._gl.TRIANGLES;
  10899. }
  10900. };
  10901. // Shaders
  10902. Engine.prototype._releaseEffect = function (effect) {
  10903. if (this._compiledEffects[effect._key]) {
  10904. delete this._compiledEffects[effect._key];
  10905. this._deleteProgram(effect.getProgram());
  10906. }
  10907. };
  10908. Engine.prototype._deleteProgram = function (program) {
  10909. if (program) {
  10910. program.__SPECTOR_rebuildProgram = null;
  10911. if (program.transformFeedback) {
  10912. this.deleteTransformFeedback(program.transformFeedback);
  10913. program.transformFeedback = null;
  10914. }
  10915. this._gl.deleteProgram(program);
  10916. }
  10917. };
  10918. /**
  10919. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10920. * @param samplers An array of string used to represent textures
  10921. */
  10922. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10923. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10924. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10925. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10926. if (this._compiledEffects[name]) {
  10927. var compiledEffect = this._compiledEffects[name];
  10928. if (onCompiled && compiledEffect.isReady()) {
  10929. onCompiled(compiledEffect);
  10930. }
  10931. return compiledEffect;
  10932. }
  10933. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10934. effect._key = name;
  10935. this._compiledEffects[name] = effect;
  10936. return effect;
  10937. };
  10938. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10939. if (uniformsNames === void 0) { uniformsNames = []; }
  10940. if (samplers === void 0) { samplers = []; }
  10941. if (defines === void 0) { defines = ""; }
  10942. return this.createEffect({
  10943. vertex: "particles",
  10944. fragmentElement: fragmentName
  10945. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10946. };
  10947. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10948. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10949. context = context || this._gl;
  10950. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10951. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10952. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10953. };
  10954. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10955. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10956. context = context || this._gl;
  10957. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10958. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10959. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10960. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10961. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10962. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10963. return program;
  10964. };
  10965. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10966. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10967. var shaderProgram = context.createProgram();
  10968. if (!shaderProgram) {
  10969. throw new Error("Unable to create program");
  10970. }
  10971. context.attachShader(shaderProgram, vertexShader);
  10972. context.attachShader(shaderProgram, fragmentShader);
  10973. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10974. var transformFeedback = this.createTransformFeedback();
  10975. this.bindTransformFeedback(transformFeedback);
  10976. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10977. shaderProgram.transformFeedback = transformFeedback;
  10978. }
  10979. context.linkProgram(shaderProgram);
  10980. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10981. this.bindTransformFeedback(null);
  10982. }
  10983. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10984. if (!linked) {
  10985. context.validateProgram(shaderProgram);
  10986. var error = context.getProgramInfoLog(shaderProgram);
  10987. if (error) {
  10988. throw new Error(error);
  10989. }
  10990. }
  10991. context.deleteShader(vertexShader);
  10992. context.deleteShader(fragmentShader);
  10993. return shaderProgram;
  10994. };
  10995. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10996. var results = new Array();
  10997. for (var index = 0; index < uniformsNames.length; index++) {
  10998. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10999. }
  11000. return results;
  11001. };
  11002. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11003. var results = [];
  11004. for (var index = 0; index < attributesNames.length; index++) {
  11005. try {
  11006. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11007. }
  11008. catch (e) {
  11009. results.push(-1);
  11010. }
  11011. }
  11012. return results;
  11013. };
  11014. Engine.prototype.enableEffect = function (effect) {
  11015. if (!effect) {
  11016. return;
  11017. }
  11018. // Use program
  11019. this.bindSamplers(effect);
  11020. this._currentEffect = effect;
  11021. if (effect.onBind) {
  11022. effect.onBind(effect);
  11023. }
  11024. effect.onBindObservable.notifyObservers(effect);
  11025. };
  11026. Engine.prototype.setIntArray = function (uniform, array) {
  11027. if (!uniform)
  11028. return;
  11029. this._gl.uniform1iv(uniform, array);
  11030. };
  11031. Engine.prototype.setIntArray2 = function (uniform, array) {
  11032. if (!uniform || array.length % 2 !== 0)
  11033. return;
  11034. this._gl.uniform2iv(uniform, array);
  11035. };
  11036. Engine.prototype.setIntArray3 = function (uniform, array) {
  11037. if (!uniform || array.length % 3 !== 0)
  11038. return;
  11039. this._gl.uniform3iv(uniform, array);
  11040. };
  11041. Engine.prototype.setIntArray4 = function (uniform, array) {
  11042. if (!uniform || array.length % 4 !== 0)
  11043. return;
  11044. this._gl.uniform4iv(uniform, array);
  11045. };
  11046. Engine.prototype.setFloatArray = function (uniform, array) {
  11047. if (!uniform)
  11048. return;
  11049. this._gl.uniform1fv(uniform, array);
  11050. };
  11051. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11052. if (!uniform || array.length % 2 !== 0)
  11053. return;
  11054. this._gl.uniform2fv(uniform, array);
  11055. };
  11056. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11057. if (!uniform || array.length % 3 !== 0)
  11058. return;
  11059. this._gl.uniform3fv(uniform, array);
  11060. };
  11061. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11062. if (!uniform || array.length % 4 !== 0)
  11063. return;
  11064. this._gl.uniform4fv(uniform, array);
  11065. };
  11066. Engine.prototype.setArray = function (uniform, array) {
  11067. if (!uniform)
  11068. return;
  11069. this._gl.uniform1fv(uniform, array);
  11070. };
  11071. Engine.prototype.setArray2 = function (uniform, array) {
  11072. if (!uniform || array.length % 2 !== 0)
  11073. return;
  11074. this._gl.uniform2fv(uniform, array);
  11075. };
  11076. Engine.prototype.setArray3 = function (uniform, array) {
  11077. if (!uniform || array.length % 3 !== 0)
  11078. return;
  11079. this._gl.uniform3fv(uniform, array);
  11080. };
  11081. Engine.prototype.setArray4 = function (uniform, array) {
  11082. if (!uniform || array.length % 4 !== 0)
  11083. return;
  11084. this._gl.uniform4fv(uniform, array);
  11085. };
  11086. Engine.prototype.setMatrices = function (uniform, matrices) {
  11087. if (!uniform)
  11088. return;
  11089. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11090. };
  11091. Engine.prototype.setMatrix = function (uniform, matrix) {
  11092. if (!uniform)
  11093. return;
  11094. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11095. };
  11096. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11097. if (!uniform)
  11098. return;
  11099. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11100. };
  11101. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11102. if (!uniform)
  11103. return;
  11104. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11105. };
  11106. Engine.prototype.setInt = function (uniform, value) {
  11107. if (!uniform)
  11108. return;
  11109. this._gl.uniform1i(uniform, value);
  11110. };
  11111. Engine.prototype.setFloat = function (uniform, value) {
  11112. if (!uniform)
  11113. return;
  11114. this._gl.uniform1f(uniform, value);
  11115. };
  11116. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11117. if (!uniform)
  11118. return;
  11119. this._gl.uniform2f(uniform, x, y);
  11120. };
  11121. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11122. if (!uniform)
  11123. return;
  11124. this._gl.uniform3f(uniform, x, y, z);
  11125. };
  11126. Engine.prototype.setBool = function (uniform, bool) {
  11127. if (!uniform)
  11128. return;
  11129. this._gl.uniform1i(uniform, bool);
  11130. };
  11131. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11132. if (!uniform)
  11133. return;
  11134. this._gl.uniform4f(uniform, x, y, z, w);
  11135. };
  11136. Engine.prototype.setColor3 = function (uniform, color3) {
  11137. if (!uniform)
  11138. return;
  11139. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11140. };
  11141. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11142. if (!uniform)
  11143. return;
  11144. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11145. };
  11146. // States
  11147. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11148. if (zOffset === void 0) { zOffset = 0; }
  11149. if (reverseSide === void 0) { reverseSide = false; }
  11150. // Culling
  11151. if (this._depthCullingState.cull !== culling || force) {
  11152. this._depthCullingState.cull = culling;
  11153. }
  11154. // Cull face
  11155. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11156. if (this._depthCullingState.cullFace !== cullFace || force) {
  11157. this._depthCullingState.cullFace = cullFace;
  11158. }
  11159. // Z offset
  11160. this.setZOffset(zOffset);
  11161. // Front face
  11162. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11163. if (this._depthCullingState.frontFace !== frontFace || force) {
  11164. this._depthCullingState.frontFace = frontFace;
  11165. }
  11166. };
  11167. Engine.prototype.setZOffset = function (value) {
  11168. this._depthCullingState.zOffset = value;
  11169. };
  11170. Engine.prototype.getZOffset = function () {
  11171. return this._depthCullingState.zOffset;
  11172. };
  11173. Engine.prototype.setDepthBuffer = function (enable) {
  11174. this._depthCullingState.depthTest = enable;
  11175. };
  11176. Engine.prototype.getDepthWrite = function () {
  11177. return this._depthCullingState.depthMask;
  11178. };
  11179. Engine.prototype.setDepthWrite = function (enable) {
  11180. this._depthCullingState.depthMask = enable;
  11181. };
  11182. Engine.prototype.setColorWrite = function (enable) {
  11183. this._gl.colorMask(enable, enable, enable, enable);
  11184. this._colorWrite = enable;
  11185. };
  11186. Engine.prototype.getColorWrite = function () {
  11187. return this._colorWrite;
  11188. };
  11189. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11190. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11191. };
  11192. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11193. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11194. if (this._alphaMode === mode) {
  11195. return;
  11196. }
  11197. switch (mode) {
  11198. case Engine.ALPHA_DISABLE:
  11199. this._alphaState.alphaBlend = false;
  11200. break;
  11201. case Engine.ALPHA_PREMULTIPLIED:
  11202. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11203. this._alphaState.alphaBlend = true;
  11204. break;
  11205. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11206. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11207. this._alphaState.alphaBlend = true;
  11208. break;
  11209. case Engine.ALPHA_COMBINE:
  11210. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11211. this._alphaState.alphaBlend = true;
  11212. break;
  11213. case Engine.ALPHA_ONEONE:
  11214. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11215. this._alphaState.alphaBlend = true;
  11216. break;
  11217. case Engine.ALPHA_ADD:
  11218. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11219. this._alphaState.alphaBlend = true;
  11220. break;
  11221. case Engine.ALPHA_SUBTRACT:
  11222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11223. this._alphaState.alphaBlend = true;
  11224. break;
  11225. case Engine.ALPHA_MULTIPLY:
  11226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11227. this._alphaState.alphaBlend = true;
  11228. break;
  11229. case Engine.ALPHA_MAXIMIZED:
  11230. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11231. this._alphaState.alphaBlend = true;
  11232. break;
  11233. case Engine.ALPHA_INTERPOLATE:
  11234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11235. this._alphaState.alphaBlend = true;
  11236. break;
  11237. case Engine.ALPHA_SCREENMODE:
  11238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11239. this._alphaState.alphaBlend = true;
  11240. break;
  11241. }
  11242. if (!noDepthWriteChange) {
  11243. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11244. }
  11245. this._alphaMode = mode;
  11246. };
  11247. Engine.prototype.getAlphaMode = function () {
  11248. return this._alphaMode;
  11249. };
  11250. Engine.prototype.setAlphaTesting = function (enable) {
  11251. this._alphaTest = enable;
  11252. };
  11253. Engine.prototype.getAlphaTesting = function () {
  11254. return !!this._alphaTest;
  11255. };
  11256. // Textures
  11257. Engine.prototype.wipeCaches = function (bruteForce) {
  11258. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11259. return;
  11260. }
  11261. this._currentEffect = null;
  11262. // 6/8/2017: deltakosh: Should not be required anymore.
  11263. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11264. if (bruteForce) {
  11265. this.resetTextureCache();
  11266. this._currentProgram = null;
  11267. this._stencilState.reset();
  11268. this._depthCullingState.reset();
  11269. this.setDepthFunctionToLessOrEqual();
  11270. this._alphaState.reset();
  11271. }
  11272. this._resetVertexBufferBinding();
  11273. this._cachedIndexBuffer = null;
  11274. this._cachedEffectForVertexBuffers = null;
  11275. this._unbindVertexArrayObject();
  11276. this.bindIndexBuffer(null);
  11277. };
  11278. /**
  11279. * Set the compressed texture format to use, based on the formats you have, and the formats
  11280. * supported by the hardware / browser.
  11281. *
  11282. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11283. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11284. * to API arguments needed to compressed textures. This puts the burden on the container
  11285. * generator to house the arcane code for determining these for current & future formats.
  11286. *
  11287. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11288. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11289. *
  11290. * Note: The result of this call is not taken into account when a texture is base64.
  11291. *
  11292. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11293. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11294. *
  11295. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11296. * @returns The extension selected.
  11297. */
  11298. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11299. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11300. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11301. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11302. return this._textureFormatInUse = this._texturesSupported[i];
  11303. }
  11304. }
  11305. }
  11306. // actively set format to nothing, to allow this to be called more than once
  11307. // and possibly fail the 2nd time
  11308. this._textureFormatInUse = null;
  11309. return null;
  11310. };
  11311. Engine.prototype._createTexture = function () {
  11312. var texture = this._gl.createTexture();
  11313. if (!texture) {
  11314. throw new Error("Unable to create texture");
  11315. }
  11316. return texture;
  11317. };
  11318. /**
  11319. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11320. * @param {string} urlArg- This contains one of the following:
  11321. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11322. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11323. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11324. *
  11325. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11326. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11327. * @param {Scene} scene- Needed for loading to the correct scene.
  11328. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11329. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11330. * @param {callback} onError- Optional callback to be called upon failure.
  11331. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11332. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11333. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11334. *
  11335. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11336. */
  11337. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11338. var _this = this;
  11339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11340. if (onLoad === void 0) { onLoad = null; }
  11341. if (onError === void 0) { onError = null; }
  11342. if (buffer === void 0) { buffer = null; }
  11343. if (fallBack === void 0) { fallBack = null; }
  11344. if (format === void 0) { format = null; }
  11345. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11346. var fromData = url.substr(0, 5) === "data:";
  11347. var fromBlob = url.substr(0, 5) === "blob:";
  11348. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11349. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11350. // establish the file extension, if possible
  11351. var lastDot = url.lastIndexOf('.');
  11352. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11353. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11354. var isTGA = (extension === ".tga");
  11355. // determine if a ktx file should be substituted
  11356. var isKTX = false;
  11357. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11358. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11359. isKTX = true;
  11360. }
  11361. if (scene) {
  11362. scene._addPendingData(texture);
  11363. }
  11364. texture.url = url;
  11365. texture.generateMipMaps = !noMipmap;
  11366. texture.samplingMode = samplingMode;
  11367. texture.invertY = invertY;
  11368. if (!this._doNotHandleContextLost) {
  11369. // Keep a link to the buffer only if we plan to handle context lost
  11370. texture._buffer = buffer;
  11371. }
  11372. var onLoadObserver = null;
  11373. if (onLoad && !fallBack) {
  11374. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11375. }
  11376. if (!fallBack)
  11377. this._internalTexturesCache.push(texture);
  11378. var onerror = function (message, exception) {
  11379. if (scene) {
  11380. scene._removePendingData(texture);
  11381. }
  11382. if (onLoadObserver) {
  11383. texture.onLoadedObservable.remove(onLoadObserver);
  11384. }
  11385. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11386. if (isKTX) {
  11387. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11388. }
  11389. else if (BABYLON.Tools.UseFallbackTexture) {
  11390. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11391. }
  11392. if (onError) {
  11393. onError(message || "Unknown error", exception);
  11394. }
  11395. };
  11396. var callback = null;
  11397. // processing for non-image formats
  11398. if (isKTX || isTGA || isDDS) {
  11399. if (isKTX) {
  11400. callback = function (data) {
  11401. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11402. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11403. ktx.uploadLevels(_this._gl, !noMipmap);
  11404. return false;
  11405. }, samplingMode);
  11406. };
  11407. }
  11408. else if (isTGA) {
  11409. callback = function (arrayBuffer) {
  11410. var data = new Uint8Array(arrayBuffer);
  11411. var header = BABYLON.TGATools.GetTGAHeader(data);
  11412. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11413. BABYLON.TGATools.UploadContent(_this._gl, data);
  11414. return false;
  11415. }, samplingMode);
  11416. };
  11417. }
  11418. else if (isDDS) {
  11419. callback = function (data) {
  11420. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11421. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11422. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11423. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11424. return false;
  11425. }, samplingMode);
  11426. };
  11427. }
  11428. if (!buffer) {
  11429. this._loadFile(url, function (data) {
  11430. if (callback) {
  11431. callback(data);
  11432. }
  11433. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11434. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11435. });
  11436. }
  11437. else {
  11438. if (callback) {
  11439. callback(buffer);
  11440. }
  11441. }
  11442. // image format processing
  11443. }
  11444. else {
  11445. var onload = function (img) {
  11446. if (fromBlob && !_this._doNotHandleContextLost) {
  11447. // We need to store the image if we need to rebuild the texture
  11448. // in case of a webgl context lost
  11449. texture._buffer = img;
  11450. }
  11451. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11452. var gl = _this._gl;
  11453. var isPot = (img.width === potWidth && img.height === potHeight);
  11454. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11455. if (isPot) {
  11456. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11457. return false;
  11458. }
  11459. // Using shaders to rescale because canvas.drawImage is lossy
  11460. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11461. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11462. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11463. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11464. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11465. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11467. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11468. _this._releaseTexture(source);
  11469. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11470. continuationCallback();
  11471. });
  11472. return true;
  11473. }, samplingMode);
  11474. };
  11475. if (!fromData || isBase64)
  11476. if (buffer instanceof HTMLImageElement) {
  11477. onload(buffer);
  11478. }
  11479. else {
  11480. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11481. }
  11482. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11483. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11484. else
  11485. onload(buffer);
  11486. }
  11487. return texture;
  11488. };
  11489. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11490. var _this = this;
  11491. var rtt = this.createRenderTargetTexture({
  11492. width: destination.width,
  11493. height: destination.height,
  11494. }, {
  11495. generateMipMaps: false,
  11496. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11497. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11498. generateDepthBuffer: false,
  11499. generateStencilBuffer: false
  11500. });
  11501. if (!this._rescalePostProcess) {
  11502. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11503. }
  11504. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11505. _this._rescalePostProcess.onApply = function (effect) {
  11506. effect._bindTexture("textureSampler", source);
  11507. };
  11508. var hostingScene = scene;
  11509. if (!hostingScene) {
  11510. hostingScene = _this.scenes[_this.scenes.length - 1];
  11511. }
  11512. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11513. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11514. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11515. _this.unBindFramebuffer(rtt);
  11516. _this._releaseTexture(rtt);
  11517. if (onComplete) {
  11518. onComplete();
  11519. }
  11520. });
  11521. };
  11522. Engine.prototype._getInternalFormat = function (format) {
  11523. var internalFormat = this._gl.RGBA;
  11524. switch (format) {
  11525. case Engine.TEXTUREFORMAT_ALPHA:
  11526. internalFormat = this._gl.ALPHA;
  11527. break;
  11528. case Engine.TEXTUREFORMAT_LUMINANCE:
  11529. internalFormat = this._gl.LUMINANCE;
  11530. break;
  11531. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11532. internalFormat = this._gl.LUMINANCE_ALPHA;
  11533. break;
  11534. case Engine.TEXTUREFORMAT_RGB:
  11535. internalFormat = this._gl.RGB;
  11536. break;
  11537. case Engine.TEXTUREFORMAT_RGBA:
  11538. internalFormat = this._gl.RGBA;
  11539. break;
  11540. }
  11541. return internalFormat;
  11542. };
  11543. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11544. if (compression === void 0) { compression = null; }
  11545. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11546. if (!texture) {
  11547. return;
  11548. }
  11549. var internalFormat = this._getInternalFormat(format);
  11550. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11551. var textureType = this._getWebGLTextureType(type);
  11552. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11553. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11554. if (!this._doNotHandleContextLost) {
  11555. texture._bufferView = data;
  11556. texture.format = format;
  11557. texture.type = type;
  11558. texture.invertY = invertY;
  11559. texture._compression = compression;
  11560. }
  11561. if (texture.width % 4 !== 0) {
  11562. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11563. }
  11564. if (compression && data) {
  11565. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11566. }
  11567. else {
  11568. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11569. }
  11570. if (texture.generateMipMaps) {
  11571. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11572. }
  11573. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11574. // this.resetTextureCache();
  11575. texture.isReady = true;
  11576. };
  11577. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11578. if (compression === void 0) { compression = null; }
  11579. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11580. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11581. texture.baseWidth = width;
  11582. texture.baseHeight = height;
  11583. texture.width = width;
  11584. texture.height = height;
  11585. texture.format = format;
  11586. texture.generateMipMaps = generateMipMaps;
  11587. texture.samplingMode = samplingMode;
  11588. texture.invertY = invertY;
  11589. texture._compression = compression;
  11590. texture.type = type;
  11591. if (!this._doNotHandleContextLost) {
  11592. texture._bufferView = data;
  11593. }
  11594. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11595. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11596. // Filters
  11597. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11600. if (generateMipMaps) {
  11601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11602. }
  11603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11604. this._internalTexturesCache.push(texture);
  11605. return texture;
  11606. };
  11607. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11608. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11609. texture.baseWidth = width;
  11610. texture.baseHeight = height;
  11611. if (generateMipMaps) {
  11612. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11613. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11614. }
  11615. // this.resetTextureCache();
  11616. texture.width = width;
  11617. texture.height = height;
  11618. texture.isReady = false;
  11619. texture.generateMipMaps = generateMipMaps;
  11620. texture.samplingMode = samplingMode;
  11621. this.updateTextureSamplingMode(samplingMode, texture);
  11622. this._internalTexturesCache.push(texture);
  11623. return texture;
  11624. };
  11625. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11626. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11627. if (texture.isCube) {
  11628. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11629. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11630. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11631. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11632. }
  11633. else if (texture.is3D) {
  11634. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11635. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11636. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11637. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11638. }
  11639. else {
  11640. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11641. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11642. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11643. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11644. }
  11645. texture.samplingMode = samplingMode;
  11646. };
  11647. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11648. if (premulAlpha === void 0) { premulAlpha = false; }
  11649. if (!texture) {
  11650. return;
  11651. }
  11652. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11653. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11654. if (premulAlpha) {
  11655. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11656. }
  11657. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11658. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11659. if (texture.generateMipMaps) {
  11660. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11661. }
  11662. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11663. if (premulAlpha) {
  11664. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11665. }
  11666. texture.isReady = true;
  11667. };
  11668. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11669. if (!texture || texture._isDisabled) {
  11670. return;
  11671. }
  11672. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11673. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11674. try {
  11675. // Testing video texture support
  11676. if (this._videoTextureSupported === undefined) {
  11677. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11678. if (this._gl.getError() !== 0) {
  11679. this._videoTextureSupported = false;
  11680. }
  11681. else {
  11682. this._videoTextureSupported = true;
  11683. }
  11684. }
  11685. // Copy video through the current working canvas if video texture is not supported
  11686. if (!this._videoTextureSupported) {
  11687. if (!texture._workingCanvas) {
  11688. texture._workingCanvas = document.createElement("canvas");
  11689. var context = texture._workingCanvas.getContext("2d");
  11690. if (!context) {
  11691. throw new Error("Unable to get 2d context");
  11692. }
  11693. texture._workingContext = context;
  11694. texture._workingCanvas.width = texture.width;
  11695. texture._workingCanvas.height = texture.height;
  11696. }
  11697. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11698. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11699. }
  11700. else {
  11701. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11702. }
  11703. if (texture.generateMipMaps) {
  11704. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11705. }
  11706. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11707. // this.resetTextureCache();
  11708. texture.isReady = true;
  11709. }
  11710. catch (ex) {
  11711. // Something unexpected
  11712. // Let's disable the texture
  11713. texture._isDisabled = true;
  11714. }
  11715. };
  11716. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11717. var fullOptions = new RenderTargetCreationOptions();
  11718. if (options !== undefined && typeof options === "object") {
  11719. fullOptions.generateMipMaps = options.generateMipMaps;
  11720. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11721. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11722. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11723. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11724. }
  11725. else {
  11726. fullOptions.generateMipMaps = options;
  11727. fullOptions.generateDepthBuffer = true;
  11728. fullOptions.generateStencilBuffer = false;
  11729. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11730. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11731. }
  11732. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11733. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11734. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11735. }
  11736. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11737. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11738. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11739. }
  11740. var gl = this._gl;
  11741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11742. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11743. var width = size.width || size;
  11744. var height = size.height || size;
  11745. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11746. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11747. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11748. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11749. }
  11750. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11751. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11752. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11753. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11754. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11755. // Create the framebuffer
  11756. var framebuffer = gl.createFramebuffer();
  11757. this.bindUnboundFramebuffer(framebuffer);
  11758. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11759. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11760. if (fullOptions.generateMipMaps) {
  11761. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11762. }
  11763. // Unbind
  11764. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11765. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11766. this.bindUnboundFramebuffer(null);
  11767. texture._framebuffer = framebuffer;
  11768. texture.baseWidth = width;
  11769. texture.baseHeight = height;
  11770. texture.width = width;
  11771. texture.height = height;
  11772. texture.isReady = true;
  11773. texture.samples = 1;
  11774. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11775. texture.samplingMode = fullOptions.samplingMode;
  11776. texture.type = fullOptions.type;
  11777. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11778. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11779. // this.resetTextureCache();
  11780. this._internalTexturesCache.push(texture);
  11781. return texture;
  11782. };
  11783. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11784. var generateMipMaps = false;
  11785. var generateDepthBuffer = true;
  11786. var generateStencilBuffer = false;
  11787. var generateDepthTexture = false;
  11788. var textureCount = 1;
  11789. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11790. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11791. var types = [], samplingModes = [];
  11792. if (options !== undefined) {
  11793. generateMipMaps = options.generateMipMaps;
  11794. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11795. generateStencilBuffer = options.generateStencilBuffer;
  11796. generateDepthTexture = options.generateDepthTexture;
  11797. textureCount = options.textureCount || 1;
  11798. if (options.types) {
  11799. types = options.types;
  11800. }
  11801. if (options.samplingModes) {
  11802. samplingModes = options.samplingModes;
  11803. }
  11804. }
  11805. var gl = this._gl;
  11806. // Create the framebuffer
  11807. var framebuffer = gl.createFramebuffer();
  11808. this.bindUnboundFramebuffer(framebuffer);
  11809. var width = size.width || size;
  11810. var height = size.height || size;
  11811. var textures = [];
  11812. var attachments = [];
  11813. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11814. for (var i = 0; i < textureCount; i++) {
  11815. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11816. var type = types[i] || defaultType;
  11817. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11818. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11819. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11820. }
  11821. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11822. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11823. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11824. }
  11825. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11826. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11827. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11828. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11829. }
  11830. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11831. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11832. textures.push(texture);
  11833. attachments.push(attachment);
  11834. gl.activeTexture(gl["TEXTURE" + i]);
  11835. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11836. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11837. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11838. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11839. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11840. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11841. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11842. if (generateMipMaps) {
  11843. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11844. }
  11845. // Unbind
  11846. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11847. texture._framebuffer = framebuffer;
  11848. texture._depthStencilBuffer = depthStencilBuffer;
  11849. texture.baseWidth = width;
  11850. texture.baseHeight = height;
  11851. texture.width = width;
  11852. texture.height = height;
  11853. texture.isReady = true;
  11854. texture.samples = 1;
  11855. texture.generateMipMaps = generateMipMaps;
  11856. texture.samplingMode = samplingMode;
  11857. texture.type = type;
  11858. texture._generateDepthBuffer = generateDepthBuffer;
  11859. texture._generateStencilBuffer = generateStencilBuffer;
  11860. texture._attachments = attachments;
  11861. this._internalTexturesCache.push(texture);
  11862. }
  11863. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11864. // Depth texture
  11865. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11866. gl.activeTexture(gl.TEXTURE0);
  11867. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11872. 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);
  11873. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11874. depthTexture._framebuffer = framebuffer;
  11875. depthTexture.baseWidth = width;
  11876. depthTexture.baseHeight = height;
  11877. depthTexture.width = width;
  11878. depthTexture.height = height;
  11879. depthTexture.isReady = true;
  11880. depthTexture.samples = 1;
  11881. depthTexture.generateMipMaps = generateMipMaps;
  11882. depthTexture.samplingMode = gl.NEAREST;
  11883. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11884. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11885. textures.push(depthTexture);
  11886. this._internalTexturesCache.push(depthTexture);
  11887. }
  11888. gl.drawBuffers(attachments);
  11889. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11890. this.bindUnboundFramebuffer(null);
  11891. this.resetTextureCache();
  11892. return textures;
  11893. };
  11894. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11895. if (samples === void 0) { samples = 1; }
  11896. var depthStencilBuffer = null;
  11897. var gl = this._gl;
  11898. // Create the depth/stencil buffer
  11899. if (generateStencilBuffer) {
  11900. depthStencilBuffer = gl.createRenderbuffer();
  11901. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11902. if (samples > 1) {
  11903. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11904. }
  11905. else {
  11906. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11907. }
  11908. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11909. }
  11910. else if (generateDepthBuffer) {
  11911. depthStencilBuffer = gl.createRenderbuffer();
  11912. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11913. if (samples > 1) {
  11914. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11915. }
  11916. else {
  11917. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11918. }
  11919. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11920. }
  11921. return depthStencilBuffer;
  11922. };
  11923. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11924. if (this.webGLVersion < 2 || !texture) {
  11925. return 1;
  11926. }
  11927. if (texture.samples === samples) {
  11928. return samples;
  11929. }
  11930. var gl = this._gl;
  11931. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11932. // Dispose previous render buffers
  11933. if (texture._depthStencilBuffer) {
  11934. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11935. texture._depthStencilBuffer = null;
  11936. }
  11937. if (texture._MSAAFramebuffer) {
  11938. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11939. texture._MSAAFramebuffer = null;
  11940. }
  11941. if (texture._MSAARenderBuffer) {
  11942. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11943. texture._MSAARenderBuffer = null;
  11944. }
  11945. if (samples > 1) {
  11946. var framebuffer = gl.createFramebuffer();
  11947. if (!framebuffer) {
  11948. throw new Error("Unable to create multi sampled framebuffer");
  11949. }
  11950. texture._MSAAFramebuffer = framebuffer;
  11951. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11952. var colorRenderbuffer = gl.createRenderbuffer();
  11953. if (!colorRenderbuffer) {
  11954. throw new Error("Unable to create multi sampled framebuffer");
  11955. }
  11956. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11957. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11958. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11959. texture._MSAARenderBuffer = colorRenderbuffer;
  11960. }
  11961. else {
  11962. this.bindUnboundFramebuffer(texture._framebuffer);
  11963. }
  11964. texture.samples = samples;
  11965. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11966. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11967. this.bindUnboundFramebuffer(null);
  11968. return samples;
  11969. };
  11970. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11971. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11972. return 1;
  11973. }
  11974. if (textures[0].samples === samples) {
  11975. return samples;
  11976. }
  11977. var gl = this._gl;
  11978. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11979. // Dispose previous render buffers
  11980. if (textures[0]._depthStencilBuffer) {
  11981. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11982. textures[0]._depthStencilBuffer = null;
  11983. }
  11984. if (textures[0]._MSAAFramebuffer) {
  11985. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11986. textures[0]._MSAAFramebuffer = null;
  11987. }
  11988. for (var i = 0; i < textures.length; i++) {
  11989. if (textures[i]._MSAARenderBuffer) {
  11990. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11991. textures[i]._MSAARenderBuffer = null;
  11992. }
  11993. }
  11994. if (samples > 1) {
  11995. var framebuffer = gl.createFramebuffer();
  11996. if (!framebuffer) {
  11997. throw new Error("Unable to create multi sampled framebuffer");
  11998. }
  11999. this.bindUnboundFramebuffer(framebuffer);
  12000. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12001. var attachments = [];
  12002. for (var i = 0; i < textures.length; i++) {
  12003. var texture = textures[i];
  12004. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12005. var colorRenderbuffer = gl.createRenderbuffer();
  12006. if (!colorRenderbuffer) {
  12007. throw new Error("Unable to create multi sampled framebuffer");
  12008. }
  12009. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12010. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12011. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12012. texture._MSAAFramebuffer = framebuffer;
  12013. texture._MSAARenderBuffer = colorRenderbuffer;
  12014. texture.samples = samples;
  12015. texture._depthStencilBuffer = depthStencilBuffer;
  12016. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12017. attachments.push(attachment);
  12018. }
  12019. gl.drawBuffers(attachments);
  12020. }
  12021. else {
  12022. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12023. }
  12024. this.bindUnboundFramebuffer(null);
  12025. return samples;
  12026. };
  12027. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12028. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12029. };
  12030. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12031. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12032. };
  12033. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12034. var gl = this._gl;
  12035. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12036. var generateMipMaps = true;
  12037. var generateDepthBuffer = true;
  12038. var generateStencilBuffer = false;
  12039. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12040. if (options !== undefined) {
  12041. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12042. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12043. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12044. if (options.samplingMode !== undefined) {
  12045. samplingMode = options.samplingMode;
  12046. }
  12047. }
  12048. texture.isCube = true;
  12049. texture.generateMipMaps = generateMipMaps;
  12050. texture.samples = 1;
  12051. texture.samplingMode = samplingMode;
  12052. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12053. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12054. for (var face = 0; face < 6; face++) {
  12055. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12056. }
  12057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12061. // Create the framebuffer
  12062. var framebuffer = gl.createFramebuffer();
  12063. this.bindUnboundFramebuffer(framebuffer);
  12064. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12065. // Mipmaps
  12066. if (texture.generateMipMaps) {
  12067. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12068. }
  12069. // Unbind
  12070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12071. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12072. this.bindUnboundFramebuffer(null);
  12073. texture._framebuffer = framebuffer;
  12074. texture.width = size;
  12075. texture.height = size;
  12076. texture.isReady = true;
  12077. //this.resetTextureCache();
  12078. this._internalTexturesCache.push(texture);
  12079. return texture;
  12080. };
  12081. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12082. var _this = this;
  12083. if (onLoad === void 0) { onLoad = null; }
  12084. if (onError === void 0) { onError = null; }
  12085. if (forcedExtension === void 0) { forcedExtension = null; }
  12086. var callback = function (loadData) {
  12087. if (!loadData) {
  12088. if (onLoad) {
  12089. onLoad(null);
  12090. }
  12091. return;
  12092. }
  12093. var texture = loadData.texture;
  12094. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12095. texture._lodGenerationScale = scale;
  12096. texture._lodGenerationOffset = offset;
  12097. if (_this._caps.textureLOD) {
  12098. // Do not add extra process if texture lod is supported.
  12099. if (onLoad) {
  12100. onLoad(texture);
  12101. }
  12102. return;
  12103. }
  12104. var mipSlices = 3;
  12105. var gl = _this._gl;
  12106. var width = loadData.width;
  12107. if (!width) {
  12108. return;
  12109. }
  12110. var textures = [];
  12111. for (var i = 0; i < mipSlices; i++) {
  12112. //compute LOD from even spacing in smoothness (matching shader calculation)
  12113. var smoothness = i / (mipSlices - 1);
  12114. var roughness = 1 - smoothness;
  12115. var minLODIndex = offset; // roughness = 0
  12116. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12117. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12118. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12119. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12120. glTextureFromLod.isCube = true;
  12121. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12124. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12126. if (loadData.isDDS) {
  12127. var info = loadData.info;
  12128. var data = loadData.data;
  12129. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12130. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12131. }
  12132. else {
  12133. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12134. }
  12135. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12136. // Wrap in a base texture for easy binding.
  12137. var lodTexture = new BABYLON.BaseTexture(scene);
  12138. lodTexture.isCube = true;
  12139. lodTexture._texture = glTextureFromLod;
  12140. glTextureFromLod.isReady = true;
  12141. textures.push(lodTexture);
  12142. }
  12143. texture._lodTextureHigh = textures[2];
  12144. texture._lodTextureMid = textures[1];
  12145. texture._lodTextureLow = textures[0];
  12146. if (onLoad) {
  12147. onLoad(texture);
  12148. }
  12149. };
  12150. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12151. };
  12152. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12153. var _this = this;
  12154. if (onLoad === void 0) { onLoad = null; }
  12155. if (onError === void 0) { onError = null; }
  12156. if (forcedExtension === void 0) { forcedExtension = null; }
  12157. var gl = this._gl;
  12158. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12159. texture.isCube = true;
  12160. texture.url = rootUrl;
  12161. texture.generateMipMaps = !noMipmap;
  12162. if (!this._doNotHandleContextLost) {
  12163. texture._extension = forcedExtension;
  12164. texture._files = files;
  12165. }
  12166. var isKTX = false;
  12167. var isDDS = false;
  12168. var lastDot = rootUrl.lastIndexOf('.');
  12169. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12170. if (this._textureFormatInUse) {
  12171. extension = this._textureFormatInUse;
  12172. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12173. isKTX = true;
  12174. }
  12175. else {
  12176. isDDS = (extension === ".dds");
  12177. }
  12178. var onerror = function (request, exception) {
  12179. if (onError && request) {
  12180. onError(request.status + " " + request.statusText, exception);
  12181. }
  12182. };
  12183. if (isKTX) {
  12184. this._loadFile(rootUrl, function (data) {
  12185. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12186. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12187. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12188. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12189. ktx.uploadLevels(_this._gl, !noMipmap);
  12190. _this.setCubeMapTextureParams(gl, loadMipmap);
  12191. texture.width = ktx.pixelWidth;
  12192. texture.height = ktx.pixelHeight;
  12193. texture.isReady = true;
  12194. }, undefined, undefined, true, onerror);
  12195. }
  12196. else if (isDDS) {
  12197. if (files && files.length === 6) {
  12198. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12199. var info;
  12200. var loadMipmap = false;
  12201. var width = 0;
  12202. for (var index = 0; index < imgs.length; index++) {
  12203. var data = imgs[index];
  12204. info = BABYLON.DDSTools.GetDDSInfo(data);
  12205. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12206. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12207. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12208. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12209. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12210. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12211. }
  12212. texture.width = info.width;
  12213. texture.height = info.height;
  12214. texture.type = info.textureType;
  12215. width = info.width;
  12216. }
  12217. _this.setCubeMapTextureParams(gl, loadMipmap);
  12218. texture.isReady = true;
  12219. if (onLoad) {
  12220. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12221. }
  12222. }, files, onError);
  12223. }
  12224. else {
  12225. this._loadFile(rootUrl, function (data) {
  12226. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12227. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12228. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12229. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12230. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12231. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12232. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12233. }
  12234. _this.setCubeMapTextureParams(gl, loadMipmap);
  12235. texture.width = info.width;
  12236. texture.height = info.height;
  12237. texture.isReady = true;
  12238. texture.type = info.textureType;
  12239. if (onLoad) {
  12240. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12241. }
  12242. }, undefined, undefined, true, onerror);
  12243. }
  12244. }
  12245. else {
  12246. if (!files) {
  12247. throw new Error("Cannot load cubemap because files were not defined");
  12248. }
  12249. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12250. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12251. var height = width;
  12252. _this._prepareWorkingCanvas();
  12253. if (!_this._workingCanvas || !_this._workingContext) {
  12254. return;
  12255. }
  12256. _this._workingCanvas.width = width;
  12257. _this._workingCanvas.height = height;
  12258. var faces = [
  12259. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12260. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12261. ];
  12262. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12263. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12264. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12265. for (var index = 0; index < faces.length; index++) {
  12266. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12267. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12268. }
  12269. if (!noMipmap) {
  12270. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12271. }
  12272. _this.setCubeMapTextureParams(gl, !noMipmap);
  12273. texture.width = width;
  12274. texture.height = height;
  12275. texture.isReady = true;
  12276. if (format) {
  12277. texture.format = format;
  12278. }
  12279. texture.onLoadedObservable.notifyObservers(texture);
  12280. texture.onLoadedObservable.clear();
  12281. if (onLoad) {
  12282. onLoad();
  12283. }
  12284. }, files, onError);
  12285. }
  12286. this._internalTexturesCache.push(texture);
  12287. return texture;
  12288. };
  12289. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12290. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12294. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12295. // this.resetTextureCache();
  12296. };
  12297. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12298. if (compression === void 0) { compression = null; }
  12299. if (level === void 0) { level = 0; }
  12300. texture._bufferViewArray = data;
  12301. texture.format = format;
  12302. texture.type = type;
  12303. texture.invertY = invertY;
  12304. texture._compression = compression;
  12305. var gl = this._gl;
  12306. var textureType = this._getWebGLTextureType(type);
  12307. var internalFormat = this._getInternalFormat(format);
  12308. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12309. var needConversion = false;
  12310. if (internalFormat === gl.RGB) {
  12311. internalFormat = gl.RGBA;
  12312. needConversion = true;
  12313. }
  12314. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12315. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12316. if (texture.width % 4 !== 0) {
  12317. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12318. }
  12319. // Data are known to be in +X +Y +Z -X -Y -Z
  12320. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12321. var faceData = data[faceIndex];
  12322. if (compression) {
  12323. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12324. }
  12325. else {
  12326. if (needConversion) {
  12327. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12328. }
  12329. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12330. }
  12331. }
  12332. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12333. if (isPot && texture.generateMipMaps && level === 0) {
  12334. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12335. }
  12336. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12337. // this.resetTextureCache();
  12338. texture.isReady = true;
  12339. };
  12340. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12341. if (compression === void 0) { compression = null; }
  12342. var gl = this._gl;
  12343. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12344. texture.isCube = true;
  12345. texture.generateMipMaps = generateMipMaps;
  12346. texture.format = format;
  12347. texture.type = type;
  12348. if (!this._doNotHandleContextLost) {
  12349. texture._bufferViewArray = data;
  12350. }
  12351. var textureType = this._getWebGLTextureType(type);
  12352. var internalFormat = this._getInternalFormat(format);
  12353. if (internalFormat === gl.RGB) {
  12354. internalFormat = gl.RGBA;
  12355. }
  12356. var width = size;
  12357. var height = width;
  12358. texture.width = width;
  12359. texture.height = height;
  12360. // Double check on POT to generate Mips.
  12361. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12362. if (!isPot) {
  12363. generateMipMaps = false;
  12364. }
  12365. // Upload data if needed. The texture won't be ready until then.
  12366. if (data) {
  12367. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12368. }
  12369. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12370. // Filters
  12371. if (data && generateMipMaps) {
  12372. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12373. }
  12374. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12377. }
  12378. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12381. }
  12382. else {
  12383. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12386. }
  12387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12390. return texture;
  12391. };
  12392. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12393. var _this = this;
  12394. if (onLoad === void 0) { onLoad = null; }
  12395. if (onError === void 0) { onError = null; }
  12396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12397. if (invertY === void 0) { invertY = false; }
  12398. var gl = this._gl;
  12399. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12400. scene._addPendingData(texture);
  12401. texture.url = url;
  12402. this._internalTexturesCache.push(texture);
  12403. var onerror = function (request, exception) {
  12404. scene._removePendingData(texture);
  12405. if (onError && request) {
  12406. onError(request.status + " " + request.statusText, exception);
  12407. }
  12408. };
  12409. var internalCallback = function (data) {
  12410. var width = texture.width;
  12411. var faceDataArrays = callback(data);
  12412. if (!faceDataArrays) {
  12413. return;
  12414. }
  12415. if (mipmmapGenerator) {
  12416. var textureType = _this._getWebGLTextureType(type);
  12417. var internalFormat = _this._getInternalFormat(format);
  12418. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12419. var needConversion = false;
  12420. if (internalFormat === gl.RGB) {
  12421. internalFormat = gl.RGBA;
  12422. needConversion = true;
  12423. }
  12424. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12425. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12426. var mipData = mipmmapGenerator(faceDataArrays);
  12427. for (var level = 0; level < mipData.length; level++) {
  12428. var mipSize = width >> level;
  12429. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12430. var mipFaceData = mipData[level][faceIndex];
  12431. if (needConversion) {
  12432. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12433. }
  12434. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12435. }
  12436. }
  12437. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12438. }
  12439. else {
  12440. texture.generateMipMaps = !noMipmap;
  12441. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12442. }
  12443. texture.isReady = true;
  12444. // this.resetTextureCache();
  12445. scene._removePendingData(texture);
  12446. if (onLoad) {
  12447. onLoad();
  12448. }
  12449. };
  12450. this._loadFile(url, function (data) {
  12451. internalCallback(data);
  12452. }, undefined, scene.database, true, onerror);
  12453. return texture;
  12454. };
  12455. ;
  12456. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12457. if (compression === void 0) { compression = null; }
  12458. var internalFormat = this._getInternalFormat(format);
  12459. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12460. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12461. if (!this._doNotHandleContextLost) {
  12462. texture._bufferView = data;
  12463. texture.format = format;
  12464. texture.invertY = invertY;
  12465. texture._compression = compression;
  12466. }
  12467. if (texture.width % 4 !== 0) {
  12468. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12469. }
  12470. if (compression && data) {
  12471. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12472. }
  12473. else {
  12474. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12475. }
  12476. if (texture.generateMipMaps) {
  12477. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12478. }
  12479. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12480. // this.resetTextureCache();
  12481. texture.isReady = true;
  12482. };
  12483. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12484. if (compression === void 0) { compression = null; }
  12485. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12486. texture.baseWidth = width;
  12487. texture.baseHeight = height;
  12488. texture.baseDepth = depth;
  12489. texture.width = width;
  12490. texture.height = height;
  12491. texture.depth = depth;
  12492. texture.format = format;
  12493. texture.generateMipMaps = generateMipMaps;
  12494. texture.samplingMode = samplingMode;
  12495. texture.is3D = true;
  12496. if (!this._doNotHandleContextLost) {
  12497. texture._bufferView = data;
  12498. }
  12499. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12500. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12501. // Filters
  12502. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12503. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12504. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12505. if (generateMipMaps) {
  12506. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12507. }
  12508. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12509. this._internalTexturesCache.push(texture);
  12510. return texture;
  12511. };
  12512. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12513. var gl = this._gl;
  12514. if (!gl) {
  12515. return;
  12516. }
  12517. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12519. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12520. if (!noMipmap && !isCompressed) {
  12521. gl.generateMipmap(gl.TEXTURE_2D);
  12522. }
  12523. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12524. // this.resetTextureCache();
  12525. if (scene) {
  12526. scene._removePendingData(texture);
  12527. }
  12528. texture.onLoadedObservable.notifyObservers(texture);
  12529. texture.onLoadedObservable.clear();
  12530. };
  12531. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12532. var _this = this;
  12533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12534. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12535. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12536. var gl = this._gl;
  12537. if (!gl) {
  12538. return;
  12539. }
  12540. if (!texture._webGLTexture) {
  12541. // this.resetTextureCache();
  12542. if (scene) {
  12543. scene._removePendingData(texture);
  12544. }
  12545. return;
  12546. }
  12547. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12548. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12549. texture.baseWidth = width;
  12550. texture.baseHeight = height;
  12551. texture.width = potWidth;
  12552. texture.height = potHeight;
  12553. texture.isReady = true;
  12554. if (processFunction(potWidth, potHeight, function () {
  12555. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12556. })) {
  12557. // Returning as texture needs extra async steps
  12558. return;
  12559. }
  12560. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12561. };
  12562. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12563. // Create new RGBA data container.
  12564. var rgbaData;
  12565. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12566. rgbaData = new Float32Array(width * height * 4);
  12567. }
  12568. else {
  12569. rgbaData = new Uint32Array(width * height * 4);
  12570. }
  12571. // Convert each pixel.
  12572. for (var x = 0; x < width; x++) {
  12573. for (var y = 0; y < height; y++) {
  12574. var index = (y * width + x) * 3;
  12575. var newIndex = (y * width + x) * 4;
  12576. // Map Old Value to new value.
  12577. rgbaData[newIndex + 0] = rgbData[index + 0];
  12578. rgbaData[newIndex + 1] = rgbData[index + 1];
  12579. rgbaData[newIndex + 2] = rgbData[index + 2];
  12580. // Add fully opaque alpha channel.
  12581. rgbaData[newIndex + 3] = 1;
  12582. }
  12583. }
  12584. return rgbaData;
  12585. };
  12586. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12587. var gl = this._gl;
  12588. if (texture._framebuffer) {
  12589. gl.deleteFramebuffer(texture._framebuffer);
  12590. texture._framebuffer = null;
  12591. }
  12592. if (texture._depthStencilBuffer) {
  12593. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12594. texture._depthStencilBuffer = null;
  12595. }
  12596. if (texture._MSAAFramebuffer) {
  12597. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12598. texture._MSAAFramebuffer = null;
  12599. }
  12600. if (texture._MSAARenderBuffer) {
  12601. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12602. texture._MSAARenderBuffer = null;
  12603. }
  12604. };
  12605. Engine.prototype._releaseTexture = function (texture) {
  12606. var gl = this._gl;
  12607. this._releaseFramebufferObjects(texture);
  12608. gl.deleteTexture(texture._webGLTexture);
  12609. // Unbind channels
  12610. this.unbindAllTextures();
  12611. var index = this._internalTexturesCache.indexOf(texture);
  12612. if (index !== -1) {
  12613. this._internalTexturesCache.splice(index, 1);
  12614. }
  12615. // Integrated fixed lod samplers.
  12616. if (texture._lodTextureHigh) {
  12617. texture._lodTextureHigh.dispose();
  12618. }
  12619. if (texture._lodTextureMid) {
  12620. texture._lodTextureMid.dispose();
  12621. }
  12622. if (texture._lodTextureLow) {
  12623. texture._lodTextureLow.dispose();
  12624. }
  12625. };
  12626. Engine.prototype.setProgram = function (program) {
  12627. if (this._currentProgram !== program) {
  12628. this._gl.useProgram(program);
  12629. this._currentProgram = program;
  12630. }
  12631. };
  12632. Engine.prototype.bindSamplers = function (effect) {
  12633. this.setProgram(effect.getProgram());
  12634. var samplers = effect.getSamplers();
  12635. for (var index = 0; index < samplers.length; index++) {
  12636. var uniform = effect.getUniform(samplers[index]);
  12637. if (uniform) {
  12638. this._boundUniforms[index] = uniform;
  12639. }
  12640. }
  12641. this._currentEffect = null;
  12642. };
  12643. Engine.prototype._activateTextureChannel = function (channel) {
  12644. if (this._activeChannel !== channel && channel > -1) {
  12645. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12646. this._activeChannel = channel;
  12647. }
  12648. };
  12649. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12650. var index = this._boundTexturesStack.indexOf(internalTexture);
  12651. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12652. this._boundTexturesStack.splice(index, 1);
  12653. this._boundTexturesStack.push(internalTexture);
  12654. }
  12655. };
  12656. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12657. var currentSlot = internalTexture._designatedSlot;
  12658. internalTexture._designatedSlot = -1;
  12659. var index = this._boundTexturesStack.indexOf(internalTexture);
  12660. if (index > -1) {
  12661. this._boundTexturesStack.splice(index, 1);
  12662. if (currentSlot > -1) {
  12663. this._boundTexturesCache[currentSlot] = null;
  12664. this._nextFreeTextureSlots.push(currentSlot);
  12665. }
  12666. }
  12667. return currentSlot;
  12668. };
  12669. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12670. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12671. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12672. var isTextureForRendering = texture && texture._initialSlot > -1;
  12673. if (currentTextureBound !== texture) {
  12674. if (currentTextureBound) {
  12675. this._removeDesignatedSlot(currentTextureBound);
  12676. }
  12677. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12678. if (this._activeChannel >= 0) {
  12679. this._boundTexturesCache[this._activeChannel] = texture;
  12680. if (isTextureForRendering) {
  12681. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12682. if (slotIndex > -1) {
  12683. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12684. }
  12685. this._boundTexturesStack.push(texture);
  12686. }
  12687. }
  12688. }
  12689. if (isTextureForRendering && this._activeChannel > -1) {
  12690. texture._designatedSlot = this._activeChannel;
  12691. if (!doNotBindUniformToTextureChannel) {
  12692. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12693. }
  12694. }
  12695. };
  12696. Engine.prototype._bindTexture = function (channel, texture) {
  12697. if (channel < 0) {
  12698. return;
  12699. }
  12700. if (texture) {
  12701. channel = this._getCorrectTextureChannel(channel, texture);
  12702. }
  12703. this._activateTextureChannel(channel);
  12704. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12705. };
  12706. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12707. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12708. };
  12709. Engine.prototype.unbindAllTextures = function () {
  12710. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  12711. this._activateTextureChannel(channel);
  12712. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12713. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12714. if (this.webGLVersion > 1) {
  12715. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12716. }
  12717. }
  12718. };
  12719. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12720. if (channel < 0) {
  12721. return;
  12722. }
  12723. if (uniform) {
  12724. this._boundUniforms[channel] = uniform;
  12725. }
  12726. this._setTexture(channel, texture);
  12727. };
  12728. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12729. if (!internalTexture) {
  12730. return -1;
  12731. }
  12732. internalTexture._initialSlot = channel;
  12733. if (channel !== internalTexture._designatedSlot) {
  12734. if (internalTexture._designatedSlot > -1) {
  12735. return internalTexture._designatedSlot;
  12736. }
  12737. else {
  12738. // No slot for this texture, let's pick a new one (if we find a free slot)
  12739. if (this._nextFreeTextureSlots.length) {
  12740. return this._nextFreeTextureSlots[0];
  12741. }
  12742. // We need to recycle the oldest bound texture, sorry.
  12743. this._textureCollisions.addCount(1, false);
  12744. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12745. }
  12746. }
  12747. return channel;
  12748. };
  12749. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12750. var uniform = this._boundUniforms[sourceSlot];
  12751. this._gl.uniform1i(uniform, destination);
  12752. };
  12753. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12754. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12755. // Not ready?
  12756. if (!texture) {
  12757. if (this._boundTexturesCache[channel] != null) {
  12758. this._activateTextureChannel(channel);
  12759. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12760. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12761. if (this.webGLVersion > 1) {
  12762. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12763. }
  12764. }
  12765. return false;
  12766. }
  12767. // Video
  12768. var alreadyActivated = false;
  12769. if (texture.video) {
  12770. this._activateTextureChannel(channel);
  12771. alreadyActivated = true;
  12772. texture.update();
  12773. }
  12774. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12775. texture.delayLoad();
  12776. return false;
  12777. }
  12778. var internalTexture;
  12779. if (texture.isReady()) {
  12780. internalTexture = texture.getInternalTexture();
  12781. }
  12782. else if (texture.isCube) {
  12783. internalTexture = this.emptyCubeTexture;
  12784. }
  12785. else if (texture.is3D) {
  12786. internalTexture = this.emptyTexture3D;
  12787. }
  12788. else {
  12789. internalTexture = this.emptyTexture;
  12790. }
  12791. if (!isPartOfTextureArray) {
  12792. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12793. }
  12794. if (this._boundTexturesCache[channel] === internalTexture) {
  12795. this._moveBoundTextureOnTop(internalTexture);
  12796. if (!isPartOfTextureArray) {
  12797. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12798. }
  12799. return false;
  12800. }
  12801. if (!alreadyActivated) {
  12802. this._activateTextureChannel(channel);
  12803. }
  12804. if (internalTexture && internalTexture.is3D) {
  12805. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12806. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12807. internalTexture._cachedWrapU = texture.wrapU;
  12808. switch (texture.wrapU) {
  12809. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12811. break;
  12812. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12813. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12814. break;
  12815. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12817. break;
  12818. }
  12819. }
  12820. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12821. internalTexture._cachedWrapV = texture.wrapV;
  12822. switch (texture.wrapV) {
  12823. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12825. break;
  12826. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12827. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12828. break;
  12829. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12830. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12831. break;
  12832. }
  12833. }
  12834. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12835. internalTexture._cachedWrapR = texture.wrapR;
  12836. switch (texture.wrapV) {
  12837. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12838. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12839. break;
  12840. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12841. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12842. break;
  12843. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12844. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12845. break;
  12846. }
  12847. }
  12848. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12849. }
  12850. else if (internalTexture && internalTexture.isCube) {
  12851. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12852. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12853. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12854. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12855. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12856. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12857. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12858. }
  12859. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12860. }
  12861. else {
  12862. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12863. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12864. internalTexture._cachedWrapU = texture.wrapU;
  12865. switch (texture.wrapU) {
  12866. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12867. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12868. break;
  12869. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12871. break;
  12872. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12873. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12874. break;
  12875. }
  12876. }
  12877. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12878. internalTexture._cachedWrapV = texture.wrapV;
  12879. switch (texture.wrapV) {
  12880. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12881. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12882. break;
  12883. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12885. break;
  12886. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12887. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12888. break;
  12889. }
  12890. }
  12891. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12892. }
  12893. return true;
  12894. };
  12895. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12896. if (channel < 0 || !uniform) {
  12897. return;
  12898. }
  12899. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12900. this._textureUnits = new Int32Array(textures.length);
  12901. }
  12902. for (var i = 0; i < textures.length; i++) {
  12903. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12904. }
  12905. this._gl.uniform1iv(uniform, this._textureUnits);
  12906. for (var index = 0; index < textures.length; index++) {
  12907. this._setTexture(this._textureUnits[index], textures[index], true);
  12908. }
  12909. };
  12910. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12911. var internalTexture = texture.getInternalTexture();
  12912. if (!internalTexture) {
  12913. return;
  12914. }
  12915. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12916. var value = texture.anisotropicFilteringLevel;
  12917. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12918. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12919. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12920. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12921. }
  12922. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12923. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12924. internalTexture._cachedAnisotropicFilteringLevel = value;
  12925. }
  12926. };
  12927. Engine.prototype.readPixels = function (x, y, width, height) {
  12928. var data = new Uint8Array(height * width * 4);
  12929. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12930. return data;
  12931. };
  12932. /**
  12933. * Add an externaly attached data from its key.
  12934. * This method call will fail and return false, if such key already exists.
  12935. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12936. * @param key the unique key that identifies the data
  12937. * @param data the data object to associate to the key for this Engine instance
  12938. * @return true if no such key were already present and the data was added successfully, false otherwise
  12939. */
  12940. Engine.prototype.addExternalData = function (key, data) {
  12941. if (!this._externalData) {
  12942. this._externalData = new BABYLON.StringDictionary();
  12943. }
  12944. return this._externalData.add(key, data);
  12945. };
  12946. /**
  12947. * Get an externaly attached data from its key
  12948. * @param key the unique key that identifies the data
  12949. * @return the associated data, if present (can be null), or undefined if not present
  12950. */
  12951. Engine.prototype.getExternalData = function (key) {
  12952. if (!this._externalData) {
  12953. this._externalData = new BABYLON.StringDictionary();
  12954. }
  12955. return this._externalData.get(key);
  12956. };
  12957. /**
  12958. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12959. * @param key the unique key that identifies the data
  12960. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12961. * @return the associated data, can be null if the factory returned null.
  12962. */
  12963. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12964. if (!this._externalData) {
  12965. this._externalData = new BABYLON.StringDictionary();
  12966. }
  12967. return this._externalData.getOrAddWithFactory(key, factory);
  12968. };
  12969. /**
  12970. * Remove an externaly attached data from the Engine instance
  12971. * @param key the unique key that identifies the data
  12972. * @return true if the data was successfully removed, false if it doesn't exist
  12973. */
  12974. Engine.prototype.removeExternalData = function (key) {
  12975. if (!this._externalData) {
  12976. this._externalData = new BABYLON.StringDictionary();
  12977. }
  12978. return this._externalData.remove(key);
  12979. };
  12980. Engine.prototype.unbindAllAttributes = function () {
  12981. if (this._mustWipeVertexAttributes) {
  12982. this._mustWipeVertexAttributes = false;
  12983. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12984. this._gl.disableVertexAttribArray(i);
  12985. this._vertexAttribArraysEnabled[i] = false;
  12986. this._currentBufferPointers[i].active = false;
  12987. }
  12988. return;
  12989. }
  12990. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12991. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12992. continue;
  12993. }
  12994. this._gl.disableVertexAttribArray(i);
  12995. this._vertexAttribArraysEnabled[i] = false;
  12996. this._currentBufferPointers[i].active = false;
  12997. }
  12998. };
  12999. Engine.prototype.releaseEffects = function () {
  13000. for (var name in this._compiledEffects) {
  13001. this._deleteProgram(this._compiledEffects[name]._program);
  13002. }
  13003. this._compiledEffects = {};
  13004. };
  13005. // Dispose
  13006. Engine.prototype.dispose = function () {
  13007. this.hideLoadingUI();
  13008. this.stopRenderLoop();
  13009. // Release postProcesses
  13010. while (this.postProcesses.length) {
  13011. this.postProcesses[0].dispose();
  13012. }
  13013. // Empty texture
  13014. if (this._emptyTexture) {
  13015. this._releaseTexture(this._emptyTexture);
  13016. this._emptyTexture = null;
  13017. }
  13018. if (this._emptyCubeTexture) {
  13019. this._releaseTexture(this._emptyCubeTexture);
  13020. this._emptyCubeTexture = null;
  13021. }
  13022. // Rescale PP
  13023. if (this._rescalePostProcess) {
  13024. this._rescalePostProcess.dispose();
  13025. }
  13026. // Release scenes
  13027. while (this.scenes.length) {
  13028. this.scenes[0].dispose();
  13029. }
  13030. // Release audio engine
  13031. if (Engine.audioEngine) {
  13032. Engine.audioEngine.dispose();
  13033. }
  13034. // Release effects
  13035. this.releaseEffects();
  13036. // Unbind
  13037. this.unbindAllAttributes();
  13038. if (this._dummyFramebuffer) {
  13039. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13040. }
  13041. //WebVR
  13042. this.disableVR();
  13043. // Events
  13044. if (BABYLON.Tools.IsWindowObjectExist()) {
  13045. window.removeEventListener("blur", this._onBlur);
  13046. window.removeEventListener("focus", this._onFocus);
  13047. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13048. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13049. if (this._renderingCanvas) {
  13050. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13051. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13052. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13053. if (!this._doNotHandleContextLost) {
  13054. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13055. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13056. }
  13057. }
  13058. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13059. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13060. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13061. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13062. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13063. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13064. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13065. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13066. if (this._onVrDisplayConnect) {
  13067. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13068. if (this._onVrDisplayDisconnect) {
  13069. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13070. }
  13071. if (this._onVrDisplayPresentChange) {
  13072. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13073. }
  13074. this._onVrDisplayConnect = null;
  13075. this._onVrDisplayDisconnect = null;
  13076. }
  13077. }
  13078. // Remove from Instances
  13079. var index = Engine.Instances.indexOf(this);
  13080. if (index >= 0) {
  13081. Engine.Instances.splice(index, 1);
  13082. }
  13083. this._workingCanvas = null;
  13084. this._workingContext = null;
  13085. this._currentBufferPointers = [];
  13086. this._renderingCanvas = null;
  13087. this._currentProgram = null;
  13088. this.onResizeObservable.clear();
  13089. this.onCanvasBlurObservable.clear();
  13090. this.onCanvasFocusObservable.clear();
  13091. this.onCanvasPointerOutObservable.clear();
  13092. this.onBeginFrameObservable.clear();
  13093. this.onEndFrameObservable.clear();
  13094. BABYLON.Effect.ResetCache();
  13095. // Abort active requests
  13096. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13097. var request = _a[_i];
  13098. request.abort();
  13099. }
  13100. };
  13101. // Loading screen
  13102. Engine.prototype.displayLoadingUI = function () {
  13103. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13104. return;
  13105. }
  13106. var loadingScreen = this.loadingScreen;
  13107. if (loadingScreen) {
  13108. loadingScreen.displayLoadingUI();
  13109. }
  13110. };
  13111. Engine.prototype.hideLoadingUI = function () {
  13112. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13113. return;
  13114. }
  13115. var loadingScreen = this.loadingScreen;
  13116. if (loadingScreen) {
  13117. loadingScreen.hideLoadingUI();
  13118. }
  13119. };
  13120. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13121. get: function () {
  13122. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13123. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13124. return this._loadingScreen;
  13125. },
  13126. set: function (loadingScreen) {
  13127. this._loadingScreen = loadingScreen;
  13128. },
  13129. enumerable: true,
  13130. configurable: true
  13131. });
  13132. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13133. set: function (text) {
  13134. this.loadingScreen.loadingUIText = text;
  13135. },
  13136. enumerable: true,
  13137. configurable: true
  13138. });
  13139. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13140. set: function (color) {
  13141. this.loadingScreen.loadingUIBackgroundColor = color;
  13142. },
  13143. enumerable: true,
  13144. configurable: true
  13145. });
  13146. Engine.prototype.attachContextLostEvent = function (callback) {
  13147. if (this._renderingCanvas) {
  13148. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13149. }
  13150. };
  13151. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13152. if (this._renderingCanvas) {
  13153. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13154. }
  13155. };
  13156. Engine.prototype.getVertexShaderSource = function (program) {
  13157. var shaders = this._gl.getAttachedShaders(program);
  13158. if (!shaders) {
  13159. return null;
  13160. }
  13161. return this._gl.getShaderSource(shaders[0]);
  13162. };
  13163. Engine.prototype.getFragmentShaderSource = function (program) {
  13164. var shaders = this._gl.getAttachedShaders(program);
  13165. if (!shaders) {
  13166. return null;
  13167. }
  13168. return this._gl.getShaderSource(shaders[1]);
  13169. };
  13170. Engine.prototype.getError = function () {
  13171. return this._gl.getError();
  13172. };
  13173. // FPS
  13174. Engine.prototype.getFps = function () {
  13175. return this._fps;
  13176. };
  13177. Engine.prototype.getDeltaTime = function () {
  13178. return this._deltaTime;
  13179. };
  13180. Engine.prototype._measureFps = function () {
  13181. this._performanceMonitor.sampleFrame();
  13182. this._fps = this._performanceMonitor.averageFPS;
  13183. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13184. };
  13185. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13186. if (faceIndex === void 0) { faceIndex = -1; }
  13187. var gl = this._gl;
  13188. if (!this._dummyFramebuffer) {
  13189. var dummy = gl.createFramebuffer();
  13190. if (!dummy) {
  13191. throw new Error("Unable to create dummy framebuffer");
  13192. }
  13193. this._dummyFramebuffer = dummy;
  13194. }
  13195. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13196. if (faceIndex > -1) {
  13197. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13198. }
  13199. else {
  13200. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13201. }
  13202. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13203. var buffer;
  13204. switch (readType) {
  13205. case gl.UNSIGNED_BYTE:
  13206. buffer = new Uint8Array(4 * width * height);
  13207. readType = gl.UNSIGNED_BYTE;
  13208. break;
  13209. default:
  13210. buffer = new Float32Array(4 * width * height);
  13211. readType = gl.FLOAT;
  13212. break;
  13213. }
  13214. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13215. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13216. return buffer;
  13217. };
  13218. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13219. if (this._webGLVersion > 1) {
  13220. return this._caps.colorBufferFloat;
  13221. }
  13222. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13223. };
  13224. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13225. if (this._webGLVersion > 1) {
  13226. return this._caps.colorBufferFloat;
  13227. }
  13228. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13229. };
  13230. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13231. Engine.prototype._canRenderToFramebuffer = function (type) {
  13232. var gl = this._gl;
  13233. //clear existing errors
  13234. while (gl.getError() !== gl.NO_ERROR) { }
  13235. var successful = true;
  13236. var texture = gl.createTexture();
  13237. gl.bindTexture(gl.TEXTURE_2D, texture);
  13238. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13241. var fb = gl.createFramebuffer();
  13242. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13243. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13244. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13245. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13246. successful = successful && (gl.getError() === gl.NO_ERROR);
  13247. //try render by clearing frame buffer's color buffer
  13248. if (successful) {
  13249. gl.clear(gl.COLOR_BUFFER_BIT);
  13250. successful = successful && (gl.getError() === gl.NO_ERROR);
  13251. }
  13252. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13253. if (successful) {
  13254. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13255. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13256. var readFormat = gl.RGBA;
  13257. var readType = gl.UNSIGNED_BYTE;
  13258. var buffer = new Uint8Array(4);
  13259. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13260. successful = successful && (gl.getError() === gl.NO_ERROR);
  13261. }
  13262. //clean up
  13263. gl.deleteTexture(texture);
  13264. gl.deleteFramebuffer(fb);
  13265. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13266. //clear accumulated errors
  13267. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13268. return successful;
  13269. };
  13270. Engine.prototype._getWebGLTextureType = function (type) {
  13271. if (type === Engine.TEXTURETYPE_FLOAT) {
  13272. return this._gl.FLOAT;
  13273. }
  13274. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13275. // Add Half Float Constant.
  13276. return this._gl.HALF_FLOAT_OES;
  13277. }
  13278. return this._gl.UNSIGNED_BYTE;
  13279. };
  13280. ;
  13281. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13282. if (this._webGLVersion === 1) {
  13283. return this._gl.RGBA;
  13284. }
  13285. if (type === Engine.TEXTURETYPE_FLOAT) {
  13286. return this._gl.RGBA32F;
  13287. }
  13288. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13289. return this._gl.RGBA16F;
  13290. }
  13291. return this._gl.RGBA;
  13292. };
  13293. ;
  13294. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13295. if (type === Engine.TEXTURETYPE_FLOAT) {
  13296. return this._gl.RGBA32F;
  13297. }
  13298. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13299. return this._gl.RGBA16F;
  13300. }
  13301. return this._gl.RGBA8;
  13302. };
  13303. ;
  13304. Engine.prototype.createQuery = function () {
  13305. return this._gl.createQuery();
  13306. };
  13307. Engine.prototype.deleteQuery = function (query) {
  13308. this._gl.deleteQuery(query);
  13309. return this;
  13310. };
  13311. Engine.prototype.isQueryResultAvailable = function (query) {
  13312. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13313. };
  13314. Engine.prototype.getQueryResult = function (query) {
  13315. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13316. };
  13317. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13318. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13319. this._gl.beginQuery(glAlgorithm, query);
  13320. return this;
  13321. };
  13322. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13323. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13324. this._gl.endQuery(glAlgorithm);
  13325. return this;
  13326. };
  13327. /* Time queries */
  13328. Engine.prototype._createTimeQuery = function () {
  13329. var timerQuery = this._caps.timerQuery;
  13330. if (timerQuery.createQueryEXT) {
  13331. return timerQuery.createQueryEXT();
  13332. }
  13333. return this.createQuery();
  13334. };
  13335. Engine.prototype._deleteTimeQuery = function (query) {
  13336. var timerQuery = this._caps.timerQuery;
  13337. if (timerQuery.deleteQueryEXT) {
  13338. timerQuery.deleteQueryEXT(query);
  13339. return;
  13340. }
  13341. this.deleteQuery(query);
  13342. };
  13343. Engine.prototype._getTimeQueryResult = function (query) {
  13344. var timerQuery = this._caps.timerQuery;
  13345. if (timerQuery.getQueryObjectEXT) {
  13346. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13347. }
  13348. return this.getQueryResult(query);
  13349. };
  13350. Engine.prototype._getTimeQueryAvailability = function (query) {
  13351. var timerQuery = this._caps.timerQuery;
  13352. if (timerQuery.getQueryObjectEXT) {
  13353. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13354. }
  13355. return this.isQueryResultAvailable(query);
  13356. };
  13357. Engine.prototype.startTimeQuery = function () {
  13358. var timerQuery = this._caps.timerQuery;
  13359. if (!timerQuery) {
  13360. return null;
  13361. }
  13362. var token = new BABYLON._TimeToken();
  13363. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13364. if (this._caps.canUseTimestampForTimerQuery) {
  13365. token._startTimeQuery = this._createTimeQuery();
  13366. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13367. }
  13368. else {
  13369. if (this._currentNonTimestampToken) {
  13370. return this._currentNonTimestampToken;
  13371. }
  13372. token._timeElapsedQuery = this._createTimeQuery();
  13373. if (timerQuery.beginQueryEXT) {
  13374. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13375. }
  13376. else {
  13377. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13378. }
  13379. this._currentNonTimestampToken = token;
  13380. }
  13381. return token;
  13382. };
  13383. Engine.prototype.endTimeQuery = function (token) {
  13384. var timerQuery = this._caps.timerQuery;
  13385. if (!timerQuery || !token) {
  13386. return -1;
  13387. }
  13388. if (this._caps.canUseTimestampForTimerQuery) {
  13389. if (!token._startTimeQuery) {
  13390. return -1;
  13391. }
  13392. if (!token._endTimeQuery) {
  13393. token._endTimeQuery = this._createTimeQuery();
  13394. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13395. }
  13396. }
  13397. else if (!token._timeElapsedQueryEnded) {
  13398. if (!token._timeElapsedQuery) {
  13399. return -1;
  13400. }
  13401. if (timerQuery.endQueryEXT) {
  13402. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13403. }
  13404. else {
  13405. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13406. }
  13407. token._timeElapsedQueryEnded = true;
  13408. }
  13409. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13410. var available = false;
  13411. if (token._endTimeQuery) {
  13412. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13413. }
  13414. else if (token._timeElapsedQuery) {
  13415. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13416. }
  13417. if (available && !disjoint) {
  13418. var result = 0;
  13419. if (this._caps.canUseTimestampForTimerQuery) {
  13420. if (!token._startTimeQuery || !token._endTimeQuery) {
  13421. return -1;
  13422. }
  13423. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13424. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13425. result = timeEnd - timeStart;
  13426. this._deleteTimeQuery(token._startTimeQuery);
  13427. this._deleteTimeQuery(token._endTimeQuery);
  13428. token._startTimeQuery = null;
  13429. token._endTimeQuery = null;
  13430. }
  13431. else {
  13432. if (!token._timeElapsedQuery) {
  13433. return -1;
  13434. }
  13435. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13436. this._deleteTimeQuery(token._timeElapsedQuery);
  13437. token._timeElapsedQuery = null;
  13438. token._timeElapsedQueryEnded = false;
  13439. this._currentNonTimestampToken = null;
  13440. }
  13441. return result;
  13442. }
  13443. return -1;
  13444. };
  13445. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13446. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13447. };
  13448. // Transform feedback
  13449. Engine.prototype.createTransformFeedback = function () {
  13450. return this._gl.createTransformFeedback();
  13451. };
  13452. Engine.prototype.deleteTransformFeedback = function (value) {
  13453. this._gl.deleteTransformFeedback(value);
  13454. };
  13455. Engine.prototype.bindTransformFeedback = function (value) {
  13456. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13457. };
  13458. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13459. if (usePoints === void 0) { usePoints = true; }
  13460. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13461. };
  13462. Engine.prototype.endTransformFeedback = function () {
  13463. this._gl.endTransformFeedback();
  13464. };
  13465. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13466. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13467. };
  13468. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13469. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13470. };
  13471. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13472. var _this = this;
  13473. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13474. this._activeRequests.push(request);
  13475. request.onCompleteObservable.add(function (request) {
  13476. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13477. });
  13478. return request;
  13479. };
  13480. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13481. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13482. var onload = function (data) {
  13483. loadedFiles[index] = data;
  13484. loadedFiles._internalCount++;
  13485. if (loadedFiles._internalCount === 6) {
  13486. onfinish(loadedFiles);
  13487. }
  13488. };
  13489. var onerror = function (request, exception) {
  13490. if (onErrorCallBack && request) {
  13491. onErrorCallBack(request.status + " " + request.statusText, exception);
  13492. }
  13493. };
  13494. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13495. };
  13496. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13497. if (onError === void 0) { onError = null; }
  13498. var loadedFiles = [];
  13499. loadedFiles._internalCount = 0;
  13500. for (var index = 0; index < 6; index++) {
  13501. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13502. }
  13503. };
  13504. // Statics
  13505. Engine.isSupported = function () {
  13506. try {
  13507. var tempcanvas = document.createElement("canvas");
  13508. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13509. return gl != null && !!window.WebGLRenderingContext;
  13510. }
  13511. catch (e) {
  13512. return false;
  13513. }
  13514. };
  13515. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13516. Engine.ExceptionList = [
  13517. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13518. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
  13519. ];
  13520. Engine.Instances = new Array();
  13521. // Const statics
  13522. Engine._ALPHA_DISABLE = 0;
  13523. Engine._ALPHA_ADD = 1;
  13524. Engine._ALPHA_COMBINE = 2;
  13525. Engine._ALPHA_SUBTRACT = 3;
  13526. Engine._ALPHA_MULTIPLY = 4;
  13527. Engine._ALPHA_MAXIMIZED = 5;
  13528. Engine._ALPHA_ONEONE = 6;
  13529. Engine._ALPHA_PREMULTIPLIED = 7;
  13530. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13531. Engine._ALPHA_INTERPOLATE = 9;
  13532. Engine._ALPHA_SCREENMODE = 10;
  13533. Engine._DELAYLOADSTATE_NONE = 0;
  13534. Engine._DELAYLOADSTATE_LOADED = 1;
  13535. Engine._DELAYLOADSTATE_LOADING = 2;
  13536. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13537. Engine._TEXTUREFORMAT_ALPHA = 0;
  13538. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13539. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13540. Engine._TEXTUREFORMAT_RGB = 4;
  13541. Engine._TEXTUREFORMAT_RGBA = 5;
  13542. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13543. Engine._TEXTURETYPE_FLOAT = 1;
  13544. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13545. // Depht or Stencil test Constants.
  13546. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13547. 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.
  13548. 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.
  13549. 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.
  13550. 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.
  13551. 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.
  13552. 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.
  13553. 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.
  13554. // Stencil Actions Constants.
  13555. Engine._KEEP = 0x1E00;
  13556. Engine._REPLACE = 0x1E01;
  13557. Engine._INCR = 0x1E02;
  13558. Engine._DECR = 0x1E03;
  13559. Engine._INVERT = 0x150A;
  13560. Engine._INCR_WRAP = 0x8507;
  13561. Engine._DECR_WRAP = 0x8508;
  13562. // Texture rescaling mode
  13563. Engine._SCALEMODE_FLOOR = 1;
  13564. Engine._SCALEMODE_NEAREST = 2;
  13565. Engine._SCALEMODE_CEILING = 3;
  13566. // Updatable statics so stick with vars here
  13567. Engine.CollisionsEpsilon = 0.001;
  13568. Engine.CodeRepository = "src/";
  13569. Engine.ShadersRepository = "src/Shaders/";
  13570. return Engine;
  13571. }());
  13572. BABYLON.Engine = Engine;
  13573. })(BABYLON || (BABYLON = {}));
  13574. //# sourceMappingURL=babylon.engine.js.map
  13575. var BABYLON;
  13576. (function (BABYLON) {
  13577. /**
  13578. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13579. */
  13580. var Node = /** @class */ (function () {
  13581. /**
  13582. * @constructor
  13583. * @param {string} name - the name and id to be given to this node
  13584. * @param {BABYLON.Scene} the scene this node will be added to
  13585. */
  13586. function Node(name, scene) {
  13587. if (scene === void 0) { scene = null; }
  13588. this.state = "";
  13589. this.metadata = null;
  13590. this.doNotSerialize = false;
  13591. this.animations = new Array();
  13592. this._ranges = {};
  13593. this._isEnabled = true;
  13594. this._isReady = true;
  13595. this._currentRenderId = -1;
  13596. this._parentRenderId = -1;
  13597. /**
  13598. * An event triggered when the mesh is disposed.
  13599. * @type {BABYLON.Observable}
  13600. */
  13601. this.onDisposeObservable = new BABYLON.Observable();
  13602. // Behaviors
  13603. this._behaviors = new Array();
  13604. this.name = name;
  13605. this.id = name;
  13606. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13607. this.uniqueId = this._scene.getUniqueId();
  13608. this._initCache();
  13609. }
  13610. Object.defineProperty(Node.prototype, "parent", {
  13611. get: function () {
  13612. return this._parentNode;
  13613. },
  13614. set: function (parent) {
  13615. if (this._parentNode === parent) {
  13616. return;
  13617. }
  13618. // Remove self from list of children of parent
  13619. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13620. var index = this._parentNode._children.indexOf(this);
  13621. if (index !== -1) {
  13622. this._parentNode._children.splice(index, 1);
  13623. }
  13624. }
  13625. // Store new parent
  13626. this._parentNode = parent;
  13627. // Add as child to new parent
  13628. if (this._parentNode) {
  13629. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13630. this._parentNode._children = new Array();
  13631. }
  13632. this._parentNode._children.push(this);
  13633. }
  13634. },
  13635. enumerable: true,
  13636. configurable: true
  13637. });
  13638. Node.prototype.getClassName = function () {
  13639. return "Node";
  13640. };
  13641. Object.defineProperty(Node.prototype, "onDispose", {
  13642. set: function (callback) {
  13643. if (this._onDisposeObserver) {
  13644. this.onDisposeObservable.remove(this._onDisposeObserver);
  13645. }
  13646. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13647. },
  13648. enumerable: true,
  13649. configurable: true
  13650. });
  13651. Node.prototype.getScene = function () {
  13652. return this._scene;
  13653. };
  13654. Node.prototype.getEngine = function () {
  13655. return this._scene.getEngine();
  13656. };
  13657. Node.prototype.addBehavior = function (behavior) {
  13658. var _this = this;
  13659. var index = this._behaviors.indexOf(behavior);
  13660. if (index !== -1) {
  13661. return this;
  13662. }
  13663. behavior.init();
  13664. if (this._scene.isLoading) {
  13665. // We defer the attach when the scene will be loaded
  13666. var observer = this._scene.onDataLoadedObservable.add(function () {
  13667. behavior.attach(_this);
  13668. setTimeout(function () {
  13669. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13670. _this._scene.onDataLoadedObservable.remove(observer);
  13671. }, 0);
  13672. });
  13673. }
  13674. else {
  13675. behavior.attach(this);
  13676. }
  13677. this._behaviors.push(behavior);
  13678. return this;
  13679. };
  13680. Node.prototype.removeBehavior = function (behavior) {
  13681. var index = this._behaviors.indexOf(behavior);
  13682. if (index === -1) {
  13683. return this;
  13684. }
  13685. this._behaviors[index].detach();
  13686. this._behaviors.splice(index, 1);
  13687. return this;
  13688. };
  13689. Object.defineProperty(Node.prototype, "behaviors", {
  13690. get: function () {
  13691. return this._behaviors;
  13692. },
  13693. enumerable: true,
  13694. configurable: true
  13695. });
  13696. Node.prototype.getBehaviorByName = function (name) {
  13697. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13698. var behavior = _a[_i];
  13699. if (behavior.name === name) {
  13700. return behavior;
  13701. }
  13702. }
  13703. return null;
  13704. };
  13705. // override it in derived class
  13706. Node.prototype.getWorldMatrix = function () {
  13707. return BABYLON.Matrix.Identity();
  13708. };
  13709. // override it in derived class if you add new variables to the cache
  13710. // and call the parent class method
  13711. Node.prototype._initCache = function () {
  13712. this._cache = {};
  13713. this._cache.parent = undefined;
  13714. };
  13715. Node.prototype.updateCache = function (force) {
  13716. if (!force && this.isSynchronized())
  13717. return;
  13718. this._cache.parent = this.parent;
  13719. this._updateCache();
  13720. };
  13721. // override it in derived class if you add new variables to the cache
  13722. // and call the parent class method if !ignoreParentClass
  13723. Node.prototype._updateCache = function (ignoreParentClass) {
  13724. };
  13725. // override it in derived class if you add new variables to the cache
  13726. Node.prototype._isSynchronized = function () {
  13727. return true;
  13728. };
  13729. Node.prototype._markSyncedWithParent = function () {
  13730. if (this.parent) {
  13731. this._parentRenderId = this.parent._currentRenderId;
  13732. }
  13733. };
  13734. Node.prototype.isSynchronizedWithParent = function () {
  13735. if (!this.parent) {
  13736. return true;
  13737. }
  13738. if (this._parentRenderId !== this.parent._currentRenderId) {
  13739. return false;
  13740. }
  13741. return this.parent.isSynchronized();
  13742. };
  13743. Node.prototype.isSynchronized = function (updateCache) {
  13744. var check = this.hasNewParent();
  13745. check = check || !this.isSynchronizedWithParent();
  13746. check = check || !this._isSynchronized();
  13747. if (updateCache)
  13748. this.updateCache(true);
  13749. return !check;
  13750. };
  13751. Node.prototype.hasNewParent = function (update) {
  13752. if (this._cache.parent === this.parent)
  13753. return false;
  13754. if (update)
  13755. this._cache.parent = this.parent;
  13756. return true;
  13757. };
  13758. /**
  13759. * Is this node ready to be used/rendered
  13760. * @return {boolean} is it ready
  13761. */
  13762. Node.prototype.isReady = function () {
  13763. return this._isReady;
  13764. };
  13765. /**
  13766. * Is this node enabled.
  13767. * 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.
  13768. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13769. * @return {boolean} whether this node (and its parent) is enabled.
  13770. * @see setEnabled
  13771. */
  13772. Node.prototype.isEnabled = function (checkAncestors) {
  13773. if (checkAncestors === void 0) { checkAncestors = true; }
  13774. if (checkAncestors === false) {
  13775. return this._isEnabled;
  13776. }
  13777. if (this._isEnabled === false) {
  13778. return false;
  13779. }
  13780. if (this.parent !== undefined && this.parent !== null) {
  13781. return this.parent.isEnabled(checkAncestors);
  13782. }
  13783. return true;
  13784. };
  13785. /**
  13786. * Set the enabled state of this node.
  13787. * @param {boolean} value - the new enabled state
  13788. * @see isEnabled
  13789. */
  13790. Node.prototype.setEnabled = function (value) {
  13791. this._isEnabled = value;
  13792. };
  13793. /**
  13794. * Is this node a descendant of the given node.
  13795. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13796. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13797. * @see parent
  13798. */
  13799. Node.prototype.isDescendantOf = function (ancestor) {
  13800. if (this.parent) {
  13801. if (this.parent === ancestor) {
  13802. return true;
  13803. }
  13804. return this.parent.isDescendantOf(ancestor);
  13805. }
  13806. return false;
  13807. };
  13808. /**
  13809. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13810. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13811. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13812. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13813. */
  13814. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13815. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13816. if (!this._children) {
  13817. return;
  13818. }
  13819. for (var index = 0; index < this._children.length; index++) {
  13820. var item = this._children[index];
  13821. if (!predicate || predicate(item)) {
  13822. results.push(item);
  13823. }
  13824. if (!directDescendantsOnly) {
  13825. item._getDescendants(results, false, predicate);
  13826. }
  13827. }
  13828. };
  13829. /**
  13830. * Will return all nodes that have this node as ascendant.
  13831. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13832. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13833. * @return {BABYLON.Node[]} all children nodes of all types.
  13834. */
  13835. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13836. var results = new Array();
  13837. this._getDescendants(results, directDescendantsOnly, predicate);
  13838. return results;
  13839. };
  13840. /**
  13841. * Get all child-meshes of this node.
  13842. */
  13843. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13844. var results = [];
  13845. this._getDescendants(results, directDescendantsOnly, function (node) {
  13846. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13847. });
  13848. return results;
  13849. };
  13850. /**
  13851. * Get all child-transformNodes of this node.
  13852. */
  13853. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13854. var results = [];
  13855. this._getDescendants(results, directDescendantsOnly, function (node) {
  13856. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13857. });
  13858. return results;
  13859. };
  13860. /**
  13861. * Get all direct children of this node.
  13862. */
  13863. Node.prototype.getChildren = function (predicate) {
  13864. return this.getDescendants(true, predicate);
  13865. };
  13866. Node.prototype._setReady = function (state) {
  13867. if (state === this._isReady) {
  13868. return;
  13869. }
  13870. if (!state) {
  13871. this._isReady = false;
  13872. return;
  13873. }
  13874. this._isReady = true;
  13875. if (this.onReady) {
  13876. this.onReady(this);
  13877. }
  13878. };
  13879. Node.prototype.getAnimationByName = function (name) {
  13880. for (var i = 0; i < this.animations.length; i++) {
  13881. var animation = this.animations[i];
  13882. if (animation.name === name) {
  13883. return animation;
  13884. }
  13885. }
  13886. return null;
  13887. };
  13888. Node.prototype.createAnimationRange = function (name, from, to) {
  13889. // check name not already in use
  13890. if (!this._ranges[name]) {
  13891. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13892. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13893. if (this.animations[i]) {
  13894. this.animations[i].createRange(name, from, to);
  13895. }
  13896. }
  13897. }
  13898. };
  13899. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13900. if (deleteFrames === void 0) { deleteFrames = true; }
  13901. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13902. if (this.animations[i]) {
  13903. this.animations[i].deleteRange(name, deleteFrames);
  13904. }
  13905. }
  13906. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13907. };
  13908. Node.prototype.getAnimationRange = function (name) {
  13909. return this._ranges[name];
  13910. };
  13911. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13912. var range = this.getAnimationRange(name);
  13913. if (!range) {
  13914. return;
  13915. }
  13916. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13917. };
  13918. Node.prototype.serializeAnimationRanges = function () {
  13919. var serializationRanges = [];
  13920. for (var name in this._ranges) {
  13921. var localRange = this._ranges[name];
  13922. if (!localRange) {
  13923. continue;
  13924. }
  13925. var range = {};
  13926. range.name = name;
  13927. range.from = localRange.from;
  13928. range.to = localRange.to;
  13929. serializationRanges.push(range);
  13930. }
  13931. return serializationRanges;
  13932. };
  13933. // override it in derived class
  13934. Node.prototype.computeWorldMatrix = function (force) {
  13935. return BABYLON.Matrix.Identity();
  13936. };
  13937. Node.prototype.dispose = function () {
  13938. this.parent = null;
  13939. // Callback
  13940. this.onDisposeObservable.notifyObservers(this);
  13941. this.onDisposeObservable.clear();
  13942. // Behaviors
  13943. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13944. var behavior = _a[_i];
  13945. behavior.detach();
  13946. }
  13947. this._behaviors = [];
  13948. };
  13949. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13950. if (parsedNode.ranges) {
  13951. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13952. var data = parsedNode.ranges[index];
  13953. node.createAnimationRange(data.name, data.from, data.to);
  13954. }
  13955. }
  13956. };
  13957. __decorate([
  13958. BABYLON.serialize()
  13959. ], Node.prototype, "name", void 0);
  13960. __decorate([
  13961. BABYLON.serialize()
  13962. ], Node.prototype, "id", void 0);
  13963. __decorate([
  13964. BABYLON.serialize()
  13965. ], Node.prototype, "uniqueId", void 0);
  13966. __decorate([
  13967. BABYLON.serialize()
  13968. ], Node.prototype, "state", void 0);
  13969. __decorate([
  13970. BABYLON.serialize()
  13971. ], Node.prototype, "metadata", void 0);
  13972. return Node;
  13973. }());
  13974. BABYLON.Node = Node;
  13975. })(BABYLON || (BABYLON = {}));
  13976. //# sourceMappingURL=babylon.node.js.map
  13977. var BABYLON;
  13978. (function (BABYLON) {
  13979. var BoundingSphere = /** @class */ (function () {
  13980. function BoundingSphere(minimum, maximum) {
  13981. this.minimum = minimum;
  13982. this.maximum = maximum;
  13983. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13984. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13985. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13986. this.radius = distance * 0.5;
  13987. this.centerWorld = BABYLON.Vector3.Zero();
  13988. this._update(BABYLON.Matrix.Identity());
  13989. }
  13990. // Methods
  13991. BoundingSphere.prototype._update = function (world) {
  13992. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13993. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13994. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  13995. };
  13996. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  13997. for (var i = 0; i < 6; i++) {
  13998. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  13999. return false;
  14000. }
  14001. return true;
  14002. };
  14003. BoundingSphere.prototype.intersectsPoint = function (point) {
  14004. var x = this.centerWorld.x - point.x;
  14005. var y = this.centerWorld.y - point.y;
  14006. var z = this.centerWorld.z - point.z;
  14007. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14008. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14009. return false;
  14010. return true;
  14011. };
  14012. // Statics
  14013. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14014. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14015. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14016. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14017. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14018. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14019. return false;
  14020. return true;
  14021. };
  14022. return BoundingSphere;
  14023. }());
  14024. BABYLON.BoundingSphere = BoundingSphere;
  14025. })(BABYLON || (BABYLON = {}));
  14026. //# sourceMappingURL=babylon.boundingSphere.js.map
  14027. var BABYLON;
  14028. (function (BABYLON) {
  14029. var BoundingBox = /** @class */ (function () {
  14030. function BoundingBox(minimum, maximum) {
  14031. this.minimum = minimum;
  14032. this.maximum = maximum;
  14033. this.vectors = new Array();
  14034. this.vectorsWorld = new Array();
  14035. // Bounding vectors
  14036. this.vectors.push(this.minimum.clone());
  14037. this.vectors.push(this.maximum.clone());
  14038. this.vectors.push(this.minimum.clone());
  14039. this.vectors[2].x = this.maximum.x;
  14040. this.vectors.push(this.minimum.clone());
  14041. this.vectors[3].y = this.maximum.y;
  14042. this.vectors.push(this.minimum.clone());
  14043. this.vectors[4].z = this.maximum.z;
  14044. this.vectors.push(this.maximum.clone());
  14045. this.vectors[5].z = this.minimum.z;
  14046. this.vectors.push(this.maximum.clone());
  14047. this.vectors[6].x = this.minimum.x;
  14048. this.vectors.push(this.maximum.clone());
  14049. this.vectors[7].y = this.minimum.y;
  14050. // OBB
  14051. this.center = this.maximum.add(this.minimum).scale(0.5);
  14052. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14053. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14054. // World
  14055. for (var index = 0; index < this.vectors.length; index++) {
  14056. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14057. }
  14058. this.minimumWorld = BABYLON.Vector3.Zero();
  14059. this.maximumWorld = BABYLON.Vector3.Zero();
  14060. this.centerWorld = BABYLON.Vector3.Zero();
  14061. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14062. this._update(BABYLON.Matrix.Identity());
  14063. }
  14064. // Methods
  14065. BoundingBox.prototype.getWorldMatrix = function () {
  14066. return this._worldMatrix;
  14067. };
  14068. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14069. this._worldMatrix.copyFrom(matrix);
  14070. return this;
  14071. };
  14072. BoundingBox.prototype._update = function (world) {
  14073. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14074. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14075. for (var index = 0; index < this.vectors.length; index++) {
  14076. var v = this.vectorsWorld[index];
  14077. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14078. if (v.x < this.minimumWorld.x)
  14079. this.minimumWorld.x = v.x;
  14080. if (v.y < this.minimumWorld.y)
  14081. this.minimumWorld.y = v.y;
  14082. if (v.z < this.minimumWorld.z)
  14083. this.minimumWorld.z = v.z;
  14084. if (v.x > this.maximumWorld.x)
  14085. this.maximumWorld.x = v.x;
  14086. if (v.y > this.maximumWorld.y)
  14087. this.maximumWorld.y = v.y;
  14088. if (v.z > this.maximumWorld.z)
  14089. this.maximumWorld.z = v.z;
  14090. }
  14091. // Extend
  14092. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14093. this.extendSizeWorld.scaleInPlace(0.5);
  14094. // OBB
  14095. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14096. this.centerWorld.scaleInPlace(0.5);
  14097. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14098. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14099. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14100. this._worldMatrix = world;
  14101. };
  14102. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14103. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14104. };
  14105. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14106. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14107. };
  14108. BoundingBox.prototype.intersectsPoint = function (point) {
  14109. var delta = -BABYLON.Epsilon;
  14110. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14111. return false;
  14112. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14113. return false;
  14114. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14115. return false;
  14116. return true;
  14117. };
  14118. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14119. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14120. };
  14121. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14122. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14123. return false;
  14124. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14125. return false;
  14126. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14127. return false;
  14128. return true;
  14129. };
  14130. // Statics
  14131. BoundingBox.Intersects = function (box0, box1) {
  14132. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14133. return false;
  14134. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14135. return false;
  14136. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14137. return false;
  14138. return true;
  14139. };
  14140. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14141. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14142. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14143. return (num <= (sphereRadius * sphereRadius));
  14144. };
  14145. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14146. for (var p = 0; p < 6; p++) {
  14147. for (var i = 0; i < 8; i++) {
  14148. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14149. return false;
  14150. }
  14151. }
  14152. }
  14153. return true;
  14154. };
  14155. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14156. for (var p = 0; p < 6; p++) {
  14157. var inCount = 8;
  14158. for (var i = 0; i < 8; i++) {
  14159. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14160. --inCount;
  14161. }
  14162. else {
  14163. break;
  14164. }
  14165. }
  14166. if (inCount === 0)
  14167. return false;
  14168. }
  14169. return true;
  14170. };
  14171. return BoundingBox;
  14172. }());
  14173. BABYLON.BoundingBox = BoundingBox;
  14174. })(BABYLON || (BABYLON = {}));
  14175. //# sourceMappingURL=babylon.boundingBox.js.map
  14176. var BABYLON;
  14177. (function (BABYLON) {
  14178. var computeBoxExtents = function (axis, box) {
  14179. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14180. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14181. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14182. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14183. var r = r0 + r1 + r2;
  14184. return {
  14185. min: p - r,
  14186. max: p + r
  14187. };
  14188. };
  14189. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14190. var axisOverlap = function (axis, box0, box1) {
  14191. var result0 = computeBoxExtents(axis, box0);
  14192. var result1 = computeBoxExtents(axis, box1);
  14193. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14194. };
  14195. var BoundingInfo = /** @class */ (function () {
  14196. function BoundingInfo(minimum, maximum) {
  14197. this.minimum = minimum;
  14198. this.maximum = maximum;
  14199. this._isLocked = false;
  14200. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14201. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14202. }
  14203. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14204. get: function () {
  14205. return this._isLocked;
  14206. },
  14207. set: function (value) {
  14208. this._isLocked = value;
  14209. },
  14210. enumerable: true,
  14211. configurable: true
  14212. });
  14213. // Methods
  14214. BoundingInfo.prototype.update = function (world) {
  14215. if (this._isLocked) {
  14216. return;
  14217. }
  14218. this.boundingBox._update(world);
  14219. this.boundingSphere._update(world);
  14220. };
  14221. /**
  14222. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14223. * @param center New center of the bounding info
  14224. * @param extend New extend of the bounding info
  14225. */
  14226. BoundingInfo.prototype.centerOn = function (center, extend) {
  14227. this.minimum = center.subtract(extend);
  14228. this.maximum = center.add(extend);
  14229. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14230. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14231. return this;
  14232. };
  14233. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14234. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14235. return false;
  14236. return this.boundingBox.isInFrustum(frustumPlanes);
  14237. };
  14238. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14239. /**
  14240. * Gets the world distance between the min and max points of the bounding box
  14241. */
  14242. get: function () {
  14243. var boundingBox = this.boundingBox;
  14244. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14245. return size.length();
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14251. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14252. };
  14253. BoundingInfo.prototype._checkCollision = function (collider) {
  14254. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14255. };
  14256. BoundingInfo.prototype.intersectsPoint = function (point) {
  14257. if (!this.boundingSphere.centerWorld) {
  14258. return false;
  14259. }
  14260. if (!this.boundingSphere.intersectsPoint(point)) {
  14261. return false;
  14262. }
  14263. if (!this.boundingBox.intersectsPoint(point)) {
  14264. return false;
  14265. }
  14266. return true;
  14267. };
  14268. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14269. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14270. return false;
  14271. }
  14272. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14273. return false;
  14274. }
  14275. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14276. return false;
  14277. }
  14278. if (!precise) {
  14279. return true;
  14280. }
  14281. var box0 = this.boundingBox;
  14282. var box1 = boundingInfo.boundingBox;
  14283. if (!axisOverlap(box0.directions[0], box0, box1))
  14284. return false;
  14285. if (!axisOverlap(box0.directions[1], box0, box1))
  14286. return false;
  14287. if (!axisOverlap(box0.directions[2], box0, box1))
  14288. return false;
  14289. if (!axisOverlap(box1.directions[0], box0, box1))
  14290. return false;
  14291. if (!axisOverlap(box1.directions[1], box0, box1))
  14292. return false;
  14293. if (!axisOverlap(box1.directions[2], box0, box1))
  14294. return false;
  14295. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14296. return false;
  14297. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14298. return false;
  14299. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14300. return false;
  14301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14302. return false;
  14303. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14304. return false;
  14305. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14306. return false;
  14307. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14308. return false;
  14309. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14310. return false;
  14311. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14312. return false;
  14313. return true;
  14314. };
  14315. return BoundingInfo;
  14316. }());
  14317. BABYLON.BoundingInfo = BoundingInfo;
  14318. })(BABYLON || (BABYLON = {}));
  14319. //# sourceMappingURL=babylon.boundingInfo.js.map
  14320. var BABYLON;
  14321. (function (BABYLON) {
  14322. var TransformNode = /** @class */ (function (_super) {
  14323. __extends(TransformNode, _super);
  14324. function TransformNode(name, scene, isPure) {
  14325. if (scene === void 0) { scene = null; }
  14326. if (isPure === void 0) { isPure = true; }
  14327. var _this = _super.call(this, name, scene) || this;
  14328. // Properties
  14329. _this._rotation = BABYLON.Vector3.Zero();
  14330. _this._scaling = BABYLON.Vector3.One();
  14331. _this._isDirty = false;
  14332. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14333. _this.scalingDeterminant = 1;
  14334. _this.infiniteDistance = false;
  14335. _this.position = BABYLON.Vector3.Zero();
  14336. _this._localWorld = BABYLON.Matrix.Zero();
  14337. _this._worldMatrix = BABYLON.Matrix.Zero();
  14338. _this._worldMatrixDeterminant = 0;
  14339. _this._absolutePosition = BABYLON.Vector3.Zero();
  14340. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14341. _this._postMultiplyPivotMatrix = false;
  14342. _this._isWorldMatrixFrozen = false;
  14343. /**
  14344. * An event triggered after the world matrix is updated
  14345. * @type {BABYLON.Observable}
  14346. */
  14347. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14348. _this._nonUniformScaling = false;
  14349. if (isPure) {
  14350. _this.getScene().addTransformNode(_this);
  14351. }
  14352. return _this;
  14353. }
  14354. Object.defineProperty(TransformNode.prototype, "rotation", {
  14355. /**
  14356. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14357. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14358. * Default : (0.0, 0.0, 0.0)
  14359. */
  14360. get: function () {
  14361. return this._rotation;
  14362. },
  14363. set: function (newRotation) {
  14364. this._rotation = newRotation;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. Object.defineProperty(TransformNode.prototype, "scaling", {
  14370. /**
  14371. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14372. * Default : (1.0, 1.0, 1.0)
  14373. */
  14374. get: function () {
  14375. return this._scaling;
  14376. },
  14377. /**
  14378. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14379. * Default : (1.0, 1.0, 1.0)
  14380. */
  14381. set: function (newScaling) {
  14382. this._scaling = newScaling;
  14383. },
  14384. enumerable: true,
  14385. configurable: true
  14386. });
  14387. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14388. /**
  14389. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14390. * It's null by default.
  14391. * 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)
  14392. */
  14393. get: function () {
  14394. return this._rotationQuaternion;
  14395. },
  14396. set: function (quaternion) {
  14397. this._rotationQuaternion = quaternion;
  14398. //reset the rotation vector.
  14399. if (quaternion && this.rotation.length()) {
  14400. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14401. }
  14402. },
  14403. enumerable: true,
  14404. configurable: true
  14405. });
  14406. /**
  14407. * Returns the latest update of the World matrix
  14408. * Returns a Matrix.
  14409. */
  14410. TransformNode.prototype.getWorldMatrix = function () {
  14411. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14412. this.computeWorldMatrix();
  14413. }
  14414. return this._worldMatrix;
  14415. };
  14416. /**
  14417. * Returns the latest update of the World matrix determinant.
  14418. */
  14419. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14420. return this._worldMatrixDeterminant;
  14421. };
  14422. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14423. /**
  14424. * Returns directly the latest state of the mesh World matrix.
  14425. * A Matrix is returned.
  14426. */
  14427. get: function () {
  14428. return this._worldMatrix;
  14429. },
  14430. enumerable: true,
  14431. configurable: true
  14432. });
  14433. /**
  14434. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14435. * Returns the AbstractMesh.
  14436. */
  14437. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14438. this._poseMatrix.copyFrom(matrix);
  14439. return this;
  14440. };
  14441. /**
  14442. * Returns the mesh Pose matrix.
  14443. * Returned object : Matrix
  14444. */
  14445. TransformNode.prototype.getPoseMatrix = function () {
  14446. return this._poseMatrix;
  14447. };
  14448. TransformNode.prototype._isSynchronized = function () {
  14449. if (this._isDirty) {
  14450. return false;
  14451. }
  14452. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14453. return false;
  14454. if (this._cache.pivotMatrixUpdated) {
  14455. return false;
  14456. }
  14457. if (this.infiniteDistance) {
  14458. return false;
  14459. }
  14460. if (!this._cache.position.equals(this.position))
  14461. return false;
  14462. if (this.rotationQuaternion) {
  14463. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14464. return false;
  14465. }
  14466. if (!this._cache.rotation.equals(this.rotation))
  14467. return false;
  14468. if (!this._cache.scaling.equals(this.scaling))
  14469. return false;
  14470. return true;
  14471. };
  14472. TransformNode.prototype._initCache = function () {
  14473. _super.prototype._initCache.call(this);
  14474. this._cache.localMatrixUpdated = false;
  14475. this._cache.position = BABYLON.Vector3.Zero();
  14476. this._cache.scaling = BABYLON.Vector3.Zero();
  14477. this._cache.rotation = BABYLON.Vector3.Zero();
  14478. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14479. this._cache.billboardMode = -1;
  14480. };
  14481. TransformNode.prototype.markAsDirty = function (property) {
  14482. if (property === "rotation") {
  14483. this.rotationQuaternion = null;
  14484. }
  14485. this._currentRenderId = Number.MAX_VALUE;
  14486. this._isDirty = true;
  14487. return this;
  14488. };
  14489. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14490. /**
  14491. * Returns the current mesh absolute position.
  14492. * Retuns a Vector3.
  14493. */
  14494. get: function () {
  14495. return this._absolutePosition;
  14496. },
  14497. enumerable: true,
  14498. configurable: true
  14499. });
  14500. /**
  14501. * Sets a new pivot matrix to the mesh.
  14502. * Returns the AbstractMesh.
  14503. */
  14504. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14505. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14506. this._pivotMatrix = matrix.clone();
  14507. this._cache.pivotMatrixUpdated = true;
  14508. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14509. if (this._postMultiplyPivotMatrix) {
  14510. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14511. }
  14512. return this;
  14513. };
  14514. /**
  14515. * Returns the mesh pivot matrix.
  14516. * Default : Identity.
  14517. * A Matrix is returned.
  14518. */
  14519. TransformNode.prototype.getPivotMatrix = function () {
  14520. return this._pivotMatrix;
  14521. };
  14522. /**
  14523. * Prevents the World matrix to be computed any longer.
  14524. * Returns the AbstractMesh.
  14525. */
  14526. TransformNode.prototype.freezeWorldMatrix = function () {
  14527. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14528. this.computeWorldMatrix(true);
  14529. this._isWorldMatrixFrozen = true;
  14530. return this;
  14531. };
  14532. /**
  14533. * Allows back the World matrix computation.
  14534. * Returns the AbstractMesh.
  14535. */
  14536. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14537. this._isWorldMatrixFrozen = false;
  14538. this.computeWorldMatrix(true);
  14539. return this;
  14540. };
  14541. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14542. /**
  14543. * True if the World matrix has been frozen.
  14544. * Returns a boolean.
  14545. */
  14546. get: function () {
  14547. return this._isWorldMatrixFrozen;
  14548. },
  14549. enumerable: true,
  14550. configurable: true
  14551. });
  14552. /**
  14553. * Retuns the mesh absolute position in the World.
  14554. * Returns a Vector3.
  14555. */
  14556. TransformNode.prototype.getAbsolutePosition = function () {
  14557. this.computeWorldMatrix();
  14558. return this._absolutePosition;
  14559. };
  14560. /**
  14561. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14562. * Returns the AbstractMesh.
  14563. */
  14564. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14565. if (!absolutePosition) {
  14566. return this;
  14567. }
  14568. var absolutePositionX;
  14569. var absolutePositionY;
  14570. var absolutePositionZ;
  14571. if (absolutePosition.x === undefined) {
  14572. if (arguments.length < 3) {
  14573. return this;
  14574. }
  14575. absolutePositionX = arguments[0];
  14576. absolutePositionY = arguments[1];
  14577. absolutePositionZ = arguments[2];
  14578. }
  14579. else {
  14580. absolutePositionX = absolutePosition.x;
  14581. absolutePositionY = absolutePosition.y;
  14582. absolutePositionZ = absolutePosition.z;
  14583. }
  14584. if (this.parent) {
  14585. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14586. invertParentWorldMatrix.invert();
  14587. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14588. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14589. }
  14590. else {
  14591. this.position.x = absolutePositionX;
  14592. this.position.y = absolutePositionY;
  14593. this.position.z = absolutePositionZ;
  14594. }
  14595. return this;
  14596. };
  14597. /**
  14598. * Sets the mesh position in its local space.
  14599. * Returns the AbstractMesh.
  14600. */
  14601. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14602. this.computeWorldMatrix();
  14603. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14604. return this;
  14605. };
  14606. /**
  14607. * Returns the mesh position in the local space from the current World matrix values.
  14608. * Returns a new Vector3.
  14609. */
  14610. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14611. this.computeWorldMatrix();
  14612. var invLocalWorldMatrix = this._localWorld.clone();
  14613. invLocalWorldMatrix.invert();
  14614. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14615. };
  14616. /**
  14617. * Translates the mesh along the passed Vector3 in its local space.
  14618. * Returns the AbstractMesh.
  14619. */
  14620. TransformNode.prototype.locallyTranslate = function (vector3) {
  14621. this.computeWorldMatrix(true);
  14622. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14623. return this;
  14624. };
  14625. /**
  14626. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14627. * @param targetPoint the position (must be in same space as current mesh) to look at
  14628. * @param yawCor optional yaw (y-axis) correction in radians
  14629. * @param pitchCor optional pitch (x-axis) correction in radians
  14630. * @param rollCor optional roll (z-axis) correction in radians
  14631. * @param space the choosen space of the target
  14632. * @returns the TransformNode.
  14633. */
  14634. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14635. if (yawCor === void 0) { yawCor = 0; }
  14636. if (pitchCor === void 0) { pitchCor = 0; }
  14637. if (rollCor === void 0) { rollCor = 0; }
  14638. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14639. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14640. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14641. targetPoint.subtractToRef(pos, dv);
  14642. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14643. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14644. var pitch = Math.atan2(dv.y, len);
  14645. if (this.rotationQuaternion) {
  14646. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14647. }
  14648. else {
  14649. this.rotation.x = pitch + pitchCor;
  14650. this.rotation.y = yaw + yawCor;
  14651. this.rotation.z = rollCor;
  14652. }
  14653. return this;
  14654. };
  14655. /**
  14656. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14657. * This Vector3 is expressed in the World space.
  14658. */
  14659. TransformNode.prototype.getDirection = function (localAxis) {
  14660. var result = BABYLON.Vector3.Zero();
  14661. this.getDirectionToRef(localAxis, result);
  14662. return result;
  14663. };
  14664. /**
  14665. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14666. * localAxis is expressed in the mesh local space.
  14667. * result is computed in the Wordl space from the mesh World matrix.
  14668. * Returns the AbstractMesh.
  14669. */
  14670. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14671. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14672. return this;
  14673. };
  14674. TransformNode.prototype.setPivotPoint = function (point, space) {
  14675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14676. if (this.getScene().getRenderId() == 0) {
  14677. this.computeWorldMatrix(true);
  14678. }
  14679. var wm = this.getWorldMatrix();
  14680. if (space == BABYLON.Space.WORLD) {
  14681. var tmat = BABYLON.Tmp.Matrix[0];
  14682. wm.invertToRef(tmat);
  14683. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14684. }
  14685. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14686. this._pivotMatrix.m[12] = -point.x;
  14687. this._pivotMatrix.m[13] = -point.y;
  14688. this._pivotMatrix.m[14] = -point.z;
  14689. this._cache.pivotMatrixUpdated = true;
  14690. return this;
  14691. };
  14692. /**
  14693. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14694. */
  14695. TransformNode.prototype.getPivotPoint = function () {
  14696. var point = BABYLON.Vector3.Zero();
  14697. this.getPivotPointToRef(point);
  14698. return point;
  14699. };
  14700. /**
  14701. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14702. * Returns the AbstractMesh.
  14703. */
  14704. TransformNode.prototype.getPivotPointToRef = function (result) {
  14705. result.x = -this._pivotMatrix.m[12];
  14706. result.y = -this._pivotMatrix.m[13];
  14707. result.z = -this._pivotMatrix.m[14];
  14708. return this;
  14709. };
  14710. /**
  14711. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14712. */
  14713. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14714. var point = BABYLON.Vector3.Zero();
  14715. this.getAbsolutePivotPointToRef(point);
  14716. return point;
  14717. };
  14718. /**
  14719. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14720. * Returns the AbstractMesh.
  14721. */
  14722. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14723. result.x = this._pivotMatrix.m[12];
  14724. result.y = this._pivotMatrix.m[13];
  14725. result.z = this._pivotMatrix.m[14];
  14726. this.getPivotPointToRef(result);
  14727. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14728. return this;
  14729. };
  14730. /**
  14731. * Defines the passed node as the parent of the current node.
  14732. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14733. * Returns the TransformNode.
  14734. */
  14735. TransformNode.prototype.setParent = function (node) {
  14736. if (node === null) {
  14737. var rotation = BABYLON.Tmp.Quaternion[0];
  14738. var position = BABYLON.Tmp.Vector3[0];
  14739. var scale = BABYLON.Tmp.Vector3[1];
  14740. if (this.parent && this.parent.computeWorldMatrix) {
  14741. this.parent.computeWorldMatrix(true);
  14742. }
  14743. this.computeWorldMatrix(true);
  14744. this.getWorldMatrix().decompose(scale, rotation, position);
  14745. if (this.rotationQuaternion) {
  14746. this.rotationQuaternion.copyFrom(rotation);
  14747. }
  14748. else {
  14749. rotation.toEulerAnglesToRef(this.rotation);
  14750. }
  14751. this.scaling.x = scale.x;
  14752. this.scaling.y = scale.y;
  14753. this.scaling.z = scale.z;
  14754. this.position.x = position.x;
  14755. this.position.y = position.y;
  14756. this.position.z = position.z;
  14757. }
  14758. else {
  14759. var rotation = BABYLON.Tmp.Quaternion[0];
  14760. var position = BABYLON.Tmp.Vector3[0];
  14761. var scale = BABYLON.Tmp.Vector3[1];
  14762. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14763. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14764. this.computeWorldMatrix(true);
  14765. node.computeWorldMatrix(true);
  14766. node.getWorldMatrix().invertToRef(invParentMatrix);
  14767. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14768. diffMatrix.decompose(scale, rotation, position);
  14769. if (this.rotationQuaternion) {
  14770. this.rotationQuaternion.copyFrom(rotation);
  14771. }
  14772. else {
  14773. rotation.toEulerAnglesToRef(this.rotation);
  14774. }
  14775. this.position.x = position.x;
  14776. this.position.y = position.y;
  14777. this.position.z = position.z;
  14778. this.scaling.x = scale.x;
  14779. this.scaling.y = scale.y;
  14780. this.scaling.z = scale.z;
  14781. }
  14782. this.parent = node;
  14783. return this;
  14784. };
  14785. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14786. get: function () {
  14787. return this._nonUniformScaling;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14793. if (this._nonUniformScaling === value) {
  14794. return false;
  14795. }
  14796. this._nonUniformScaling = true;
  14797. return true;
  14798. };
  14799. /**
  14800. * Attach the current TransformNode to another TransformNode associated with a bone
  14801. * @param bone Bone affecting the TransformNode
  14802. * @param affectedTransformNode TransformNode associated with the bone
  14803. */
  14804. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14805. this._transformToBoneReferal = affectedTransformNode;
  14806. this.parent = bone;
  14807. if (bone.getWorldMatrix().determinant() < 0) {
  14808. this.scalingDeterminant *= -1;
  14809. }
  14810. return this;
  14811. };
  14812. TransformNode.prototype.detachFromBone = function () {
  14813. if (!this.parent) {
  14814. return this;
  14815. }
  14816. if (this.parent.getWorldMatrix().determinant() < 0) {
  14817. this.scalingDeterminant *= -1;
  14818. }
  14819. this._transformToBoneReferal = null;
  14820. this.parent = null;
  14821. return this;
  14822. };
  14823. /**
  14824. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14825. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14826. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14827. * The passed axis is also normalized.
  14828. * Returns the AbstractMesh.
  14829. */
  14830. TransformNode.prototype.rotate = function (axis, amount, space) {
  14831. axis.normalize();
  14832. if (!this.rotationQuaternion) {
  14833. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14834. this.rotation = BABYLON.Vector3.Zero();
  14835. }
  14836. var rotationQuaternion;
  14837. if (!space || space === BABYLON.Space.LOCAL) {
  14838. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14839. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14840. }
  14841. else {
  14842. if (this.parent) {
  14843. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14844. invertParentWorldMatrix.invert();
  14845. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14846. }
  14847. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14848. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14849. }
  14850. return this;
  14851. };
  14852. /**
  14853. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14854. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14855. * The passed axis is also normalized.
  14856. * Returns the AbstractMesh.
  14857. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14858. */
  14859. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14860. axis.normalize();
  14861. if (!this.rotationQuaternion) {
  14862. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14863. this.rotation.copyFromFloats(0, 0, 0);
  14864. }
  14865. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14866. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14867. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14868. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14869. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14870. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14871. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14872. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14873. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14874. return this;
  14875. };
  14876. /**
  14877. * Translates the mesh along the axis vector for the passed distance in the given space.
  14878. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14879. * Returns the AbstractMesh.
  14880. */
  14881. TransformNode.prototype.translate = function (axis, distance, space) {
  14882. var displacementVector = axis.scale(distance);
  14883. if (!space || space === BABYLON.Space.LOCAL) {
  14884. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14885. this.setPositionWithLocalVector(tempV3);
  14886. }
  14887. else {
  14888. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14889. }
  14890. return this;
  14891. };
  14892. /**
  14893. * Adds a rotation step to the mesh current rotation.
  14894. * x, y, z are Euler angles expressed in radians.
  14895. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14896. * This means this rotation is made in the mesh local space only.
  14897. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14898. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14899. * ```javascript
  14900. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14901. * ```
  14902. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14903. * 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.
  14904. * Returns the AbstractMesh.
  14905. */
  14906. TransformNode.prototype.addRotation = function (x, y, z) {
  14907. var rotationQuaternion;
  14908. if (this.rotationQuaternion) {
  14909. rotationQuaternion = this.rotationQuaternion;
  14910. }
  14911. else {
  14912. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14913. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14914. }
  14915. var accumulation = BABYLON.Tmp.Quaternion[0];
  14916. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14917. rotationQuaternion.multiplyInPlace(accumulation);
  14918. if (!this.rotationQuaternion) {
  14919. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14920. }
  14921. return this;
  14922. };
  14923. /**
  14924. * Computes the mesh World matrix and returns it.
  14925. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14926. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14927. * If the parameter `force`is set to `true`, the actual computation is done.
  14928. * Returns the mesh World Matrix.
  14929. */
  14930. TransformNode.prototype.computeWorldMatrix = function (force) {
  14931. if (this._isWorldMatrixFrozen) {
  14932. return this._worldMatrix;
  14933. }
  14934. if (!force && this.isSynchronized(true)) {
  14935. return this._worldMatrix;
  14936. }
  14937. this._cache.position.copyFrom(this.position);
  14938. this._cache.scaling.copyFrom(this.scaling);
  14939. this._cache.pivotMatrixUpdated = false;
  14940. this._cache.billboardMode = this.billboardMode;
  14941. this._currentRenderId = this.getScene().getRenderId();
  14942. this._isDirty = false;
  14943. // Scaling
  14944. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14945. // Rotation
  14946. //rotate, if quaternion is set and rotation was used
  14947. if (this.rotationQuaternion) {
  14948. var len = this.rotation.length();
  14949. if (len) {
  14950. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14951. this.rotation.copyFromFloats(0, 0, 0);
  14952. }
  14953. }
  14954. if (this.rotationQuaternion) {
  14955. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14956. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14957. }
  14958. else {
  14959. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14960. this._cache.rotation.copyFrom(this.rotation);
  14961. }
  14962. // Translation
  14963. var camera = this.getScene().activeCamera;
  14964. if (this.infiniteDistance && !this.parent && camera) {
  14965. var cameraWorldMatrix = camera.getWorldMatrix();
  14966. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14967. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14968. }
  14969. else {
  14970. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14971. }
  14972. // Composing transformations
  14973. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14974. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14975. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14976. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14977. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14978. // Need to decompose each rotation here
  14979. var currentPosition = BABYLON.Tmp.Vector3[3];
  14980. if (this.parent && this.parent.getWorldMatrix) {
  14981. if (this._transformToBoneReferal) {
  14982. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14984. }
  14985. else {
  14986. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14987. }
  14988. }
  14989. else {
  14990. currentPosition.copyFrom(this.position);
  14991. }
  14992. currentPosition.subtractInPlace(camera.globalPosition);
  14993. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14994. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  14995. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14996. }
  14997. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  14998. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14999. }
  15000. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15001. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15002. }
  15003. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15004. }
  15005. else {
  15006. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15007. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15008. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15009. }
  15010. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15011. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15012. }
  15013. // Local world
  15014. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15015. // Parent
  15016. if (this.parent && this.parent.getWorldMatrix) {
  15017. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15018. if (this._transformToBoneReferal) {
  15019. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15020. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15021. }
  15022. else {
  15023. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15024. }
  15025. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15026. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15027. this._worldMatrix.copyFrom(this._localWorld);
  15028. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15029. }
  15030. else {
  15031. if (this._transformToBoneReferal) {
  15032. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15033. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15034. }
  15035. else {
  15036. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15037. }
  15038. }
  15039. this._markSyncedWithParent();
  15040. }
  15041. else {
  15042. this._worldMatrix.copyFrom(this._localWorld);
  15043. }
  15044. // Post multiply inverse of pivotMatrix
  15045. if (this._postMultiplyPivotMatrix) {
  15046. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15047. }
  15048. // Normal matrix
  15049. if (this.scaling.isNonUniform) {
  15050. this._updateNonUniformScalingState(true);
  15051. }
  15052. else if (this.parent && this.parent._nonUniformScaling) {
  15053. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15054. }
  15055. else {
  15056. this._updateNonUniformScalingState(false);
  15057. }
  15058. this._afterComputeWorldMatrix();
  15059. // Absolute position
  15060. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15061. // Callbacks
  15062. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15063. if (!this._poseMatrix) {
  15064. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15065. }
  15066. // Cache the determinant
  15067. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15068. return this._worldMatrix;
  15069. };
  15070. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15071. };
  15072. /**
  15073. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15074. * @param func: callback function to add
  15075. *
  15076. * Returns the TransformNode.
  15077. */
  15078. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15079. this.onAfterWorldMatrixUpdateObservable.add(func);
  15080. return this;
  15081. };
  15082. /**
  15083. * Removes a registered callback function.
  15084. * Returns the TransformNode.
  15085. */
  15086. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15087. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15088. return this;
  15089. };
  15090. /**
  15091. * Clone the current transform node
  15092. * Returns the new transform node
  15093. * @param name Name of the new clone
  15094. * @param newParent New parent for the clone
  15095. * @param doNotCloneChildren Do not clone children hierarchy
  15096. */
  15097. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15098. var _this = this;
  15099. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15100. result.name = name;
  15101. result.id = name;
  15102. if (newParent) {
  15103. result.parent = newParent;
  15104. }
  15105. if (!doNotCloneChildren) {
  15106. // Children
  15107. var directDescendants = this.getDescendants(true);
  15108. for (var index = 0; index < directDescendants.length; index++) {
  15109. var child = directDescendants[index];
  15110. if (child.clone) {
  15111. child.clone(name + "." + child.name, result);
  15112. }
  15113. }
  15114. }
  15115. return result;
  15116. };
  15117. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15118. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15119. serializationObject.type = this.getClassName();
  15120. // Parent
  15121. if (this.parent) {
  15122. serializationObject.parentId = this.parent.id;
  15123. }
  15124. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15125. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15126. }
  15127. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15128. serializationObject.isEnabled = this.isEnabled();
  15129. // Parent
  15130. if (this.parent) {
  15131. serializationObject.parentId = this.parent.id;
  15132. }
  15133. return serializationObject;
  15134. };
  15135. // Statics
  15136. /**
  15137. * Returns a new TransformNode object parsed from the source provided.
  15138. * The parameter `parsedMesh` is the source.
  15139. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15140. */
  15141. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15142. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15143. if (BABYLON.Tags) {
  15144. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15145. }
  15146. if (parsedTransformNode.localMatrix) {
  15147. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15148. }
  15149. else if (parsedTransformNode.pivotMatrix) {
  15150. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15151. }
  15152. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15153. // Parent
  15154. if (parsedTransformNode.parentId) {
  15155. transformNode._waitingParentId = parsedTransformNode.parentId;
  15156. }
  15157. return transformNode;
  15158. };
  15159. /**
  15160. * Disposes the TransformNode.
  15161. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15162. * Returns nothing.
  15163. */
  15164. TransformNode.prototype.dispose = function (doNotRecurse) {
  15165. // Animations
  15166. this.getScene().stopAnimation(this);
  15167. // Remove from scene
  15168. this.getScene().removeTransformNode(this);
  15169. if (!doNotRecurse) {
  15170. // Children
  15171. var objects = this.getDescendants(true);
  15172. for (var index = 0; index < objects.length; index++) {
  15173. objects[index].dispose();
  15174. }
  15175. }
  15176. else {
  15177. var childMeshes = this.getChildMeshes(true);
  15178. for (index = 0; index < childMeshes.length; index++) {
  15179. var child = childMeshes[index];
  15180. child.parent = null;
  15181. child.computeWorldMatrix(true);
  15182. }
  15183. }
  15184. this.onAfterWorldMatrixUpdateObservable.clear();
  15185. _super.prototype.dispose.call(this);
  15186. };
  15187. // Statics
  15188. TransformNode.BILLBOARDMODE_NONE = 0;
  15189. TransformNode.BILLBOARDMODE_X = 1;
  15190. TransformNode.BILLBOARDMODE_Y = 2;
  15191. TransformNode.BILLBOARDMODE_Z = 4;
  15192. TransformNode.BILLBOARDMODE_ALL = 7;
  15193. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15194. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15195. __decorate([
  15196. BABYLON.serializeAsVector3()
  15197. ], TransformNode.prototype, "_rotation", void 0);
  15198. __decorate([
  15199. BABYLON.serializeAsQuaternion()
  15200. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15201. __decorate([
  15202. BABYLON.serializeAsVector3()
  15203. ], TransformNode.prototype, "_scaling", void 0);
  15204. __decorate([
  15205. BABYLON.serialize()
  15206. ], TransformNode.prototype, "billboardMode", void 0);
  15207. __decorate([
  15208. BABYLON.serialize()
  15209. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15210. __decorate([
  15211. BABYLON.serialize()
  15212. ], TransformNode.prototype, "infiniteDistance", void 0);
  15213. __decorate([
  15214. BABYLON.serializeAsVector3()
  15215. ], TransformNode.prototype, "position", void 0);
  15216. return TransformNode;
  15217. }(BABYLON.Node));
  15218. BABYLON.TransformNode = TransformNode;
  15219. })(BABYLON || (BABYLON = {}));
  15220. //# sourceMappingURL=babylon.transformNode.js.map
  15221. var BABYLON;
  15222. (function (BABYLON) {
  15223. var AbstractMesh = /** @class */ (function (_super) {
  15224. __extends(AbstractMesh, _super);
  15225. // Constructor
  15226. function AbstractMesh(name, scene) {
  15227. if (scene === void 0) { scene = null; }
  15228. var _this = _super.call(this, name, scene, false) || this;
  15229. _this._facetNb = 0; // facet number
  15230. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15231. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15232. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15233. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15234. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15235. _this._subDiv = {
  15236. max: 1,
  15237. X: 1,
  15238. Y: 1,
  15239. Z: 1
  15240. };
  15241. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15242. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15243. // Events
  15244. /**
  15245. * An event triggered when this mesh collides with another one
  15246. * @type {BABYLON.Observable}
  15247. */
  15248. _this.onCollideObservable = new BABYLON.Observable();
  15249. /**
  15250. * An event triggered when the collision's position changes
  15251. * @type {BABYLON.Observable}
  15252. */
  15253. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15254. /**
  15255. * An event triggered when material is changed
  15256. * @type {BABYLON.Observable}
  15257. */
  15258. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15259. // Properties
  15260. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15261. /**
  15262. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15263. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15264. * or
  15265. * 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.
  15266. * for more info check WebGl documentations
  15267. */
  15268. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15269. /**
  15270. * 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:
  15271. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15272. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15273. * 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.
  15274. */
  15275. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15276. /**
  15277. * 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.
  15278. * The default value is -1 which means don't break the query and wait till the result.
  15279. */
  15280. _this.occlusionRetryCount = -1;
  15281. _this._occlusionInternalRetryCounter = 0;
  15282. _this._isOccluded = false;
  15283. _this._isOcclusionQueryInProgress = false;
  15284. _this.visibility = 1.0;
  15285. _this.alphaIndex = Number.MAX_VALUE;
  15286. _this.isVisible = true;
  15287. _this.isPickable = true;
  15288. _this.showBoundingBox = false;
  15289. _this.showSubMeshesBoundingBox = false;
  15290. _this.isBlocker = false;
  15291. _this.enablePointerMoveEvents = false;
  15292. _this.renderingGroupId = 0;
  15293. _this._receiveShadows = false;
  15294. _this.renderOutline = false;
  15295. _this.outlineColor = BABYLON.Color3.Red();
  15296. _this.outlineWidth = 0.02;
  15297. _this.renderOverlay = false;
  15298. _this.overlayColor = BABYLON.Color3.Red();
  15299. _this.overlayAlpha = 0.5;
  15300. _this._hasVertexAlpha = false;
  15301. _this._useVertexColors = true;
  15302. _this._computeBonesUsingShaders = true;
  15303. _this._numBoneInfluencers = 4;
  15304. _this._applyFog = true;
  15305. _this.useOctreeForRenderingSelection = true;
  15306. _this.useOctreeForPicking = true;
  15307. _this.useOctreeForCollisions = true;
  15308. _this._layerMask = 0x0FFFFFFF;
  15309. /**
  15310. * True if the mesh must be rendered in any case.
  15311. */
  15312. _this.alwaysSelectAsActiveMesh = false;
  15313. /**
  15314. * This scene's action manager
  15315. * @type {BABYLON.ActionManager}
  15316. */
  15317. _this.actionManager = null;
  15318. // Physics
  15319. _this.physicsImpostor = null;
  15320. // Collisions
  15321. _this._checkCollisions = false;
  15322. _this._collisionMask = -1;
  15323. _this._collisionGroup = -1;
  15324. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15325. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15326. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15327. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15328. // Edges
  15329. _this.edgesWidth = 1;
  15330. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15331. // Cache
  15332. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15333. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15334. _this._isDisposed = false;
  15335. _this._renderId = 0;
  15336. _this._intersectionsInProgress = new Array();
  15337. _this._unIndexed = false;
  15338. _this._lightSources = new Array();
  15339. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15340. if (collidedMesh === void 0) { collidedMesh = null; }
  15341. //TODO move this to the collision coordinator!
  15342. if (_this.getScene().workerCollisions)
  15343. newPosition.multiplyInPlace(_this._collider._radius);
  15344. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15345. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15346. _this.position.addInPlace(_this._diffPositionForCollisions);
  15347. }
  15348. if (collidedMesh) {
  15349. _this.onCollideObservable.notifyObservers(collidedMesh);
  15350. }
  15351. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15352. };
  15353. _this.getScene().addMesh(_this);
  15354. _this._resyncLightSources();
  15355. return _this;
  15356. }
  15357. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15358. get: function () {
  15359. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15360. },
  15361. enumerable: true,
  15362. configurable: true
  15363. });
  15364. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15365. get: function () {
  15366. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15367. },
  15368. enumerable: true,
  15369. configurable: true
  15370. });
  15371. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15372. get: function () {
  15373. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15374. },
  15375. enumerable: true,
  15376. configurable: true
  15377. });
  15378. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15379. get: function () {
  15380. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15381. },
  15382. enumerable: true,
  15383. configurable: true
  15384. });
  15385. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15386. get: function () {
  15387. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15388. },
  15389. enumerable: true,
  15390. configurable: true
  15391. });
  15392. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15393. /**
  15394. * Read-only : the number of facets in the mesh
  15395. */
  15396. get: function () {
  15397. return this._facetNb;
  15398. },
  15399. enumerable: true,
  15400. configurable: true
  15401. });
  15402. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15403. /**
  15404. * The number (integer) of subdivisions per axis in the partioning space
  15405. */
  15406. get: function () {
  15407. return this._partitioningSubdivisions;
  15408. },
  15409. set: function (nb) {
  15410. this._partitioningSubdivisions = nb;
  15411. },
  15412. enumerable: true,
  15413. configurable: true
  15414. });
  15415. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15416. /**
  15417. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15418. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15419. */
  15420. get: function () {
  15421. return this._partitioningBBoxRatio;
  15422. },
  15423. set: function (ratio) {
  15424. this._partitioningBBoxRatio = ratio;
  15425. },
  15426. enumerable: true,
  15427. configurable: true
  15428. });
  15429. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15430. /**
  15431. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15432. * Works only for updatable meshes.
  15433. * Doesn't work with multi-materials.
  15434. */
  15435. get: function () {
  15436. return this._facetDepthSort;
  15437. },
  15438. set: function (sort) {
  15439. this._facetDepthSort = sort;
  15440. },
  15441. enumerable: true,
  15442. configurable: true
  15443. });
  15444. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15445. /**
  15446. * The location (Vector3) where the facet depth sort must be computed from.
  15447. * By default, the active camera position.
  15448. * Used only when facet depth sort is enabled.
  15449. */
  15450. get: function () {
  15451. return this._facetDepthSortFrom;
  15452. },
  15453. set: function (location) {
  15454. this._facetDepthSortFrom = location;
  15455. },
  15456. enumerable: true,
  15457. configurable: true
  15458. });
  15459. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15460. /**
  15461. * Read-only boolean : is the feature facetData enabled ?
  15462. */
  15463. get: function () {
  15464. return this._facetDataEnabled;
  15465. },
  15466. enumerable: true,
  15467. configurable: true
  15468. });
  15469. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15470. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15471. return false;
  15472. }
  15473. this._markSubMeshesAsMiscDirty();
  15474. return true;
  15475. };
  15476. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15477. set: function (callback) {
  15478. if (this._onCollideObserver) {
  15479. this.onCollideObservable.remove(this._onCollideObserver);
  15480. }
  15481. this._onCollideObserver = this.onCollideObservable.add(callback);
  15482. },
  15483. enumerable: true,
  15484. configurable: true
  15485. });
  15486. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15487. set: function (callback) {
  15488. if (this._onCollisionPositionChangeObserver) {
  15489. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15490. }
  15491. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15492. },
  15493. enumerable: true,
  15494. configurable: true
  15495. });
  15496. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15497. /**
  15498. * 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.
  15499. */
  15500. get: function () {
  15501. return this._isOccluded;
  15502. },
  15503. set: function (value) {
  15504. this._isOccluded = value;
  15505. },
  15506. enumerable: true,
  15507. configurable: true
  15508. });
  15509. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15510. /**
  15511. * Flag to check the progress status of the query
  15512. */
  15513. get: function () {
  15514. return this._isOcclusionQueryInProgress;
  15515. },
  15516. enumerable: true,
  15517. configurable: true
  15518. });
  15519. Object.defineProperty(AbstractMesh.prototype, "material", {
  15520. get: function () {
  15521. return this._material;
  15522. },
  15523. set: function (value) {
  15524. if (this._material === value) {
  15525. return;
  15526. }
  15527. this._material = value;
  15528. if (this.onMaterialChangedObservable.hasObservers) {
  15529. this.onMaterialChangedObservable.notifyObservers(this);
  15530. }
  15531. if (!this.subMeshes) {
  15532. return;
  15533. }
  15534. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15535. var subMesh = _a[_i];
  15536. subMesh.setEffect(null);
  15537. }
  15538. },
  15539. enumerable: true,
  15540. configurable: true
  15541. });
  15542. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15543. get: function () {
  15544. return this._receiveShadows;
  15545. },
  15546. set: function (value) {
  15547. if (this._receiveShadows === value) {
  15548. return;
  15549. }
  15550. this._receiveShadows = value;
  15551. this._markSubMeshesAsLightDirty();
  15552. },
  15553. enumerable: true,
  15554. configurable: true
  15555. });
  15556. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15557. get: function () {
  15558. return this._hasVertexAlpha;
  15559. },
  15560. set: function (value) {
  15561. if (this._hasVertexAlpha === value) {
  15562. return;
  15563. }
  15564. this._hasVertexAlpha = value;
  15565. this._markSubMeshesAsAttributesDirty();
  15566. },
  15567. enumerable: true,
  15568. configurable: true
  15569. });
  15570. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15571. get: function () {
  15572. return this._useVertexColors;
  15573. },
  15574. set: function (value) {
  15575. if (this._useVertexColors === value) {
  15576. return;
  15577. }
  15578. this._useVertexColors = value;
  15579. this._markSubMeshesAsAttributesDirty();
  15580. },
  15581. enumerable: true,
  15582. configurable: true
  15583. });
  15584. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15585. get: function () {
  15586. return this._computeBonesUsingShaders;
  15587. },
  15588. set: function (value) {
  15589. if (this._computeBonesUsingShaders === value) {
  15590. return;
  15591. }
  15592. this._computeBonesUsingShaders = value;
  15593. this._markSubMeshesAsAttributesDirty();
  15594. },
  15595. enumerable: true,
  15596. configurable: true
  15597. });
  15598. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15599. get: function () {
  15600. return this._numBoneInfluencers;
  15601. },
  15602. set: function (value) {
  15603. if (this._numBoneInfluencers === value) {
  15604. return;
  15605. }
  15606. this._numBoneInfluencers = value;
  15607. this._markSubMeshesAsAttributesDirty();
  15608. },
  15609. enumerable: true,
  15610. configurable: true
  15611. });
  15612. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15613. get: function () {
  15614. return this._applyFog;
  15615. },
  15616. set: function (value) {
  15617. if (this._applyFog === value) {
  15618. return;
  15619. }
  15620. this._applyFog = value;
  15621. this._markSubMeshesAsMiscDirty();
  15622. },
  15623. enumerable: true,
  15624. configurable: true
  15625. });
  15626. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15627. get: function () {
  15628. return this._layerMask;
  15629. },
  15630. set: function (value) {
  15631. if (value === this._layerMask) {
  15632. return;
  15633. }
  15634. this._layerMask = value;
  15635. this._resyncLightSources();
  15636. },
  15637. enumerable: true,
  15638. configurable: true
  15639. });
  15640. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15641. get: function () {
  15642. return this._collisionMask;
  15643. },
  15644. set: function (mask) {
  15645. this._collisionMask = !isNaN(mask) ? mask : -1;
  15646. },
  15647. enumerable: true,
  15648. configurable: true
  15649. });
  15650. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15651. get: function () {
  15652. return this._collisionGroup;
  15653. },
  15654. set: function (mask) {
  15655. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15656. },
  15657. enumerable: true,
  15658. configurable: true
  15659. });
  15660. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15661. get: function () {
  15662. return null;
  15663. },
  15664. enumerable: true,
  15665. configurable: true
  15666. });
  15667. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15668. get: function () {
  15669. return this._skeleton;
  15670. },
  15671. set: function (value) {
  15672. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15673. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15674. }
  15675. if (value && value.needInitialSkinMatrix) {
  15676. value._registerMeshWithPoseMatrix(this);
  15677. }
  15678. this._skeleton = value;
  15679. if (!this._skeleton) {
  15680. this._bonesTransformMatrices = null;
  15681. }
  15682. this._markSubMeshesAsAttributesDirty();
  15683. },
  15684. enumerable: true,
  15685. configurable: true
  15686. });
  15687. /**
  15688. * Boolean : true if the mesh has been disposed.
  15689. */
  15690. AbstractMesh.prototype.isDisposed = function () {
  15691. return this._isDisposed;
  15692. };
  15693. /**
  15694. * Returns the string "AbstractMesh"
  15695. */
  15696. AbstractMesh.prototype.getClassName = function () {
  15697. return "AbstractMesh";
  15698. };
  15699. /**
  15700. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15701. */
  15702. AbstractMesh.prototype.toString = function (fullDetails) {
  15703. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15704. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15705. if (this._skeleton) {
  15706. ret += ", skeleton: " + this._skeleton.name;
  15707. }
  15708. if (fullDetails) {
  15709. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15710. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15711. }
  15712. return ret;
  15713. };
  15714. AbstractMesh.prototype._rebuild = function () {
  15715. if (this._occlusionQuery) {
  15716. this._occlusionQuery = null;
  15717. }
  15718. if (this._edgesRenderer) {
  15719. this._edgesRenderer._rebuild();
  15720. }
  15721. if (!this.subMeshes) {
  15722. return;
  15723. }
  15724. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15725. var subMesh = _a[_i];
  15726. subMesh._rebuild();
  15727. }
  15728. };
  15729. AbstractMesh.prototype._resyncLightSources = function () {
  15730. this._lightSources.length = 0;
  15731. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15732. var light = _a[_i];
  15733. if (!light.isEnabled()) {
  15734. continue;
  15735. }
  15736. if (light.canAffectMesh(this)) {
  15737. this._lightSources.push(light);
  15738. }
  15739. }
  15740. this._markSubMeshesAsLightDirty();
  15741. };
  15742. AbstractMesh.prototype._resyncLighSource = function (light) {
  15743. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15744. var index = this._lightSources.indexOf(light);
  15745. if (index === -1) {
  15746. if (!isIn) {
  15747. return;
  15748. }
  15749. this._lightSources.push(light);
  15750. }
  15751. else {
  15752. if (isIn) {
  15753. return;
  15754. }
  15755. this._lightSources.splice(index, 1);
  15756. }
  15757. this._markSubMeshesAsLightDirty();
  15758. };
  15759. AbstractMesh.prototype._removeLightSource = function (light) {
  15760. var index = this._lightSources.indexOf(light);
  15761. if (index === -1) {
  15762. return;
  15763. }
  15764. this._lightSources.splice(index, 1);
  15765. };
  15766. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15767. if (!this.subMeshes) {
  15768. return;
  15769. }
  15770. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15771. var subMesh = _a[_i];
  15772. if (subMesh._materialDefines) {
  15773. func(subMesh._materialDefines);
  15774. }
  15775. }
  15776. };
  15777. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15778. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15779. };
  15780. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15781. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15782. };
  15783. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15784. if (!this.subMeshes) {
  15785. return;
  15786. }
  15787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15788. var subMesh = _a[_i];
  15789. var material = subMesh.getMaterial();
  15790. if (material) {
  15791. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15792. }
  15793. }
  15794. };
  15795. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15796. /**
  15797. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15798. * Default : (1.0, 1.0, 1.0)
  15799. */
  15800. get: function () {
  15801. return this._scaling;
  15802. },
  15803. /**
  15804. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15805. * Default : (1.0, 1.0, 1.0)
  15806. */
  15807. set: function (newScaling) {
  15808. this._scaling = newScaling;
  15809. if (this.physicsImpostor) {
  15810. this.physicsImpostor.forceUpdate();
  15811. }
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. // Methods
  15817. /**
  15818. * Disables the mesh edger rendering mode.
  15819. * Returns the AbstractMesh.
  15820. */
  15821. AbstractMesh.prototype.disableEdgesRendering = function () {
  15822. if (this._edgesRenderer) {
  15823. this._edgesRenderer.dispose();
  15824. this._edgesRenderer = null;
  15825. }
  15826. return this;
  15827. };
  15828. /**
  15829. * Enables the edge rendering mode on the mesh.
  15830. * This mode makes the mesh edges visible.
  15831. * Returns the AbstractMesh.
  15832. */
  15833. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15834. if (epsilon === void 0) { epsilon = 0.95; }
  15835. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15836. this.disableEdgesRendering();
  15837. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15838. return this;
  15839. };
  15840. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15841. /**
  15842. * Returns true if the mesh is blocked. Used by the class Mesh.
  15843. * Returns the boolean `false` by default.
  15844. */
  15845. get: function () {
  15846. return false;
  15847. },
  15848. enumerable: true,
  15849. configurable: true
  15850. });
  15851. /**
  15852. * Returns the mesh itself by default, used by the class Mesh.
  15853. * Returned type : AbstractMesh
  15854. */
  15855. AbstractMesh.prototype.getLOD = function (camera) {
  15856. return this;
  15857. };
  15858. /**
  15859. * Returns 0 by default, used by the class Mesh.
  15860. * Returns an integer.
  15861. */
  15862. AbstractMesh.prototype.getTotalVertices = function () {
  15863. return 0;
  15864. };
  15865. /**
  15866. * Returns null by default, used by the class Mesh.
  15867. * Returned type : integer array
  15868. */
  15869. AbstractMesh.prototype.getIndices = function () {
  15870. return null;
  15871. };
  15872. /**
  15873. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15874. * Returned type : float array or Float32Array
  15875. */
  15876. AbstractMesh.prototype.getVerticesData = function (kind) {
  15877. return null;
  15878. };
  15879. /**
  15880. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15881. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15882. * The `data` are either a numeric array either a Float32Array.
  15883. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15884. * 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).
  15885. * Note that a new underlying VertexBuffer object is created each call.
  15886. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15887. *
  15888. * Possible `kind` values :
  15889. * - BABYLON.VertexBuffer.PositionKind
  15890. * - BABYLON.VertexBuffer.UVKind
  15891. * - BABYLON.VertexBuffer.UV2Kind
  15892. * - BABYLON.VertexBuffer.UV3Kind
  15893. * - BABYLON.VertexBuffer.UV4Kind
  15894. * - BABYLON.VertexBuffer.UV5Kind
  15895. * - BABYLON.VertexBuffer.UV6Kind
  15896. * - BABYLON.VertexBuffer.ColorKind
  15897. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15898. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15899. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15900. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15901. *
  15902. * Returns the Mesh.
  15903. */
  15904. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15905. return this;
  15906. };
  15907. /**
  15908. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15909. * If the mesh has no geometry, it is simply returned as it is.
  15910. * The `data` are either a numeric array either a Float32Array.
  15911. * No new underlying VertexBuffer object is created.
  15912. * 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.
  15913. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15914. *
  15915. * Possible `kind` values :
  15916. * - BABYLON.VertexBuffer.PositionKind
  15917. * - BABYLON.VertexBuffer.UVKind
  15918. * - BABYLON.VertexBuffer.UV2Kind
  15919. * - BABYLON.VertexBuffer.UV3Kind
  15920. * - BABYLON.VertexBuffer.UV4Kind
  15921. * - BABYLON.VertexBuffer.UV5Kind
  15922. * - BABYLON.VertexBuffer.UV6Kind
  15923. * - BABYLON.VertexBuffer.ColorKind
  15924. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15925. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15926. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15927. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15928. *
  15929. * Returns the Mesh.
  15930. */
  15931. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15932. return this;
  15933. };
  15934. /**
  15935. * Sets the mesh indices.
  15936. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15937. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15938. * This method creates a new index buffer each call.
  15939. * Returns the Mesh.
  15940. */
  15941. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15942. return this;
  15943. };
  15944. /** Returns false by default, used by the class Mesh.
  15945. * Returns a boolean
  15946. */
  15947. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15948. return false;
  15949. };
  15950. /**
  15951. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15952. * Returns a BoundingInfo
  15953. */
  15954. AbstractMesh.prototype.getBoundingInfo = function () {
  15955. if (this._masterMesh) {
  15956. return this._masterMesh.getBoundingInfo();
  15957. }
  15958. if (!this._boundingInfo) {
  15959. // this._boundingInfo is being created here
  15960. this._updateBoundingInfo();
  15961. }
  15962. // cannot be null.
  15963. return this._boundingInfo;
  15964. };
  15965. /**
  15966. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15967. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15968. */
  15969. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15970. if (includeDescendants === void 0) { includeDescendants = true; }
  15971. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15972. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15973. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15974. if (maxDimension === 0) {
  15975. return this;
  15976. }
  15977. var scale = 1 / maxDimension;
  15978. this.scaling.scaleInPlace(scale);
  15979. return this;
  15980. };
  15981. /**
  15982. * Sets a mesh new object BoundingInfo.
  15983. * Returns the AbstractMesh.
  15984. */
  15985. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15986. this._boundingInfo = boundingInfo;
  15987. return this;
  15988. };
  15989. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15990. get: function () {
  15991. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15992. },
  15993. enumerable: true,
  15994. configurable: true
  15995. });
  15996. AbstractMesh.prototype._preActivate = function () {
  15997. };
  15998. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  15999. };
  16000. AbstractMesh.prototype._activate = function (renderId) {
  16001. this._renderId = renderId;
  16002. };
  16003. /**
  16004. * Returns the latest update of the World matrix
  16005. * Returns a Matrix.
  16006. */
  16007. AbstractMesh.prototype.getWorldMatrix = function () {
  16008. if (this._masterMesh) {
  16009. return this._masterMesh.getWorldMatrix();
  16010. }
  16011. return _super.prototype.getWorldMatrix.call(this);
  16012. };
  16013. /**
  16014. * Returns the latest update of the World matrix determinant.
  16015. */
  16016. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16017. if (this._masterMesh) {
  16018. return this._masterMesh._getWorldMatrixDeterminant();
  16019. }
  16020. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16021. };
  16022. // ================================== Point of View Movement =================================
  16023. /**
  16024. * Perform relative position change from the point of view of behind the front of the mesh.
  16025. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16026. * Supports definition of mesh facing forward or backward.
  16027. * @param {number} amountRight
  16028. * @param {number} amountUp
  16029. * @param {number} amountForward
  16030. *
  16031. * Returns the AbstractMesh.
  16032. */
  16033. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16034. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16035. return this;
  16036. };
  16037. /**
  16038. * Calculate relative position change from the point of view of behind the front of the mesh.
  16039. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16040. * Supports definition of mesh facing forward or backward.
  16041. * @param {number} amountRight
  16042. * @param {number} amountUp
  16043. * @param {number} amountForward
  16044. *
  16045. * Returns a new Vector3.
  16046. */
  16047. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16048. var rotMatrix = new BABYLON.Matrix();
  16049. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16050. rotQuaternion.toRotationMatrix(rotMatrix);
  16051. var translationDelta = BABYLON.Vector3.Zero();
  16052. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16054. return translationDelta;
  16055. };
  16056. // ================================== Point of View Rotation =================================
  16057. /**
  16058. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16059. * Supports definition of mesh facing forward or backward.
  16060. * @param {number} flipBack
  16061. * @param {number} twirlClockwise
  16062. * @param {number} tiltRight
  16063. *
  16064. * Returns the AbstractMesh.
  16065. */
  16066. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16067. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16068. return this;
  16069. };
  16070. /**
  16071. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16072. * Supports definition of mesh facing forward or backward.
  16073. * @param {number} flipBack
  16074. * @param {number} twirlClockwise
  16075. * @param {number} tiltRight
  16076. *
  16077. * Returns a new Vector3.
  16078. */
  16079. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16080. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16081. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16082. };
  16083. /**
  16084. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16085. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16086. */
  16087. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16088. if (includeDescendants === void 0) { includeDescendants = true; }
  16089. this.computeWorldMatrix(true);
  16090. var min;
  16091. var max;
  16092. var boundingInfo = this.getBoundingInfo();
  16093. if (!this.subMeshes) {
  16094. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16095. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16096. }
  16097. else {
  16098. min = boundingInfo.boundingBox.minimumWorld;
  16099. max = boundingInfo.boundingBox.maximumWorld;
  16100. }
  16101. if (includeDescendants) {
  16102. var descendants = this.getDescendants(false);
  16103. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16104. var descendant = descendants_1[_i];
  16105. var childMesh = descendant;
  16106. childMesh.computeWorldMatrix(true);
  16107. //make sure we have the needed params to get mix and max
  16108. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16109. continue;
  16110. }
  16111. var childBoundingInfo = childMesh.getBoundingInfo();
  16112. var boundingBox = childBoundingInfo.boundingBox;
  16113. var minBox = boundingBox.minimumWorld;
  16114. var maxBox = boundingBox.maximumWorld;
  16115. BABYLON.Tools.CheckExtends(minBox, min, max);
  16116. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16117. }
  16118. }
  16119. return {
  16120. min: min,
  16121. max: max
  16122. };
  16123. };
  16124. /**
  16125. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16126. * Returns the AbstractMesh.
  16127. */
  16128. AbstractMesh.prototype._updateBoundingInfo = function () {
  16129. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16130. this._boundingInfo.update(this.worldMatrixFromCache);
  16131. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16132. return this;
  16133. };
  16134. /**
  16135. * Update a mesh's children BoundingInfo objects only.
  16136. * Returns the AbstractMesh.
  16137. */
  16138. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16139. if (!this.subMeshes) {
  16140. return this;
  16141. }
  16142. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16143. var subMesh = this.subMeshes[subIndex];
  16144. if (!subMesh.IsGlobal) {
  16145. subMesh.updateBoundingInfo(matrix);
  16146. }
  16147. }
  16148. return this;
  16149. };
  16150. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16151. // Bounding info
  16152. this._updateBoundingInfo();
  16153. };
  16154. /**
  16155. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16156. * A mesh is in the frustum if its bounding box intersects the frustum.
  16157. * Boolean returned.
  16158. */
  16159. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16160. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16161. };
  16162. /**
  16163. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16164. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16165. * Boolean returned.
  16166. */
  16167. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16168. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16169. ;
  16170. };
  16171. /**
  16172. * True if the mesh intersects another mesh or a SolidParticle object.
  16173. * 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)
  16174. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16175. * Returns a boolean.
  16176. */
  16177. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16178. if (precise === void 0) { precise = false; }
  16179. if (!this._boundingInfo || !mesh._boundingInfo) {
  16180. return false;
  16181. }
  16182. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16183. return true;
  16184. }
  16185. if (includeDescendants) {
  16186. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16187. var child = _a[_i];
  16188. if (child.intersectsMesh(mesh, precise, true)) {
  16189. return true;
  16190. }
  16191. }
  16192. }
  16193. return false;
  16194. };
  16195. /**
  16196. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16197. * Returns a boolean.
  16198. */
  16199. AbstractMesh.prototype.intersectsPoint = function (point) {
  16200. if (!this._boundingInfo) {
  16201. return false;
  16202. }
  16203. return this._boundingInfo.intersectsPoint(point);
  16204. };
  16205. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16206. return this.physicsImpostor;
  16207. };
  16208. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16209. if (camera === void 0) { camera = null; }
  16210. if (!camera) {
  16211. camera = this.getScene().activeCamera;
  16212. }
  16213. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16214. };
  16215. /**
  16216. * Returns the distance from the mesh to the active camera.
  16217. * Returns a float.
  16218. */
  16219. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16220. if (camera === void 0) { camera = null; }
  16221. if (!camera) {
  16222. camera = this.getScene().activeCamera;
  16223. }
  16224. return this.absolutePosition.subtract(camera.position).length();
  16225. };
  16226. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16227. if (!this.physicsImpostor) {
  16228. return this;
  16229. }
  16230. this.physicsImpostor.applyImpulse(force, contactPoint);
  16231. return this;
  16232. };
  16233. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16234. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16235. return this;
  16236. }
  16237. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16238. mainPivot: pivot1,
  16239. connectedPivot: pivot2,
  16240. nativeParams: options
  16241. });
  16242. return this;
  16243. };
  16244. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16245. // Collisions
  16246. /**
  16247. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16248. * Default `false`.
  16249. */
  16250. get: function () {
  16251. return this._checkCollisions;
  16252. },
  16253. set: function (collisionEnabled) {
  16254. this._checkCollisions = collisionEnabled;
  16255. if (this.getScene().workerCollisions) {
  16256. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16257. }
  16258. },
  16259. enumerable: true,
  16260. configurable: true
  16261. });
  16262. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16263. /**
  16264. * Gets Collider object used to compute collisions (not physics)
  16265. */
  16266. get: function () {
  16267. return this._collider;
  16268. },
  16269. enumerable: true,
  16270. configurable: true
  16271. });
  16272. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16273. var globalPosition = this.getAbsolutePosition();
  16274. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16275. if (!this._collider) {
  16276. this._collider = new BABYLON.Collider();
  16277. }
  16278. this._collider._radius = this.ellipsoid;
  16279. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16280. return this;
  16281. };
  16282. // Submeshes octree
  16283. /**
  16284. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16285. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16286. * Returns an Octree of submeshes.
  16287. */
  16288. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16289. if (maxCapacity === void 0) { maxCapacity = 64; }
  16290. if (maxDepth === void 0) { maxDepth = 2; }
  16291. if (!this._submeshesOctree) {
  16292. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16293. }
  16294. this.computeWorldMatrix(true);
  16295. var boundingInfo = this.getBoundingInfo();
  16296. // Update octree
  16297. var bbox = boundingInfo.boundingBox;
  16298. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16299. return this._submeshesOctree;
  16300. };
  16301. // Collisions
  16302. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16303. this._generatePointsArray();
  16304. if (!this._positions) {
  16305. return this;
  16306. }
  16307. // Transformation
  16308. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16309. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16310. subMesh._lastColliderWorldVertices = [];
  16311. subMesh._trianglePlanes = [];
  16312. var start = subMesh.verticesStart;
  16313. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16314. for (var i = start; i < end; i++) {
  16315. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16316. }
  16317. }
  16318. // Collide
  16319. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16320. if (collider.collisionFound) {
  16321. collider.collidedMesh = this;
  16322. }
  16323. return this;
  16324. };
  16325. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16326. var subMeshes;
  16327. var len;
  16328. // Octrees
  16329. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16330. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16331. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16332. len = intersections.length;
  16333. subMeshes = intersections.data;
  16334. }
  16335. else {
  16336. subMeshes = this.subMeshes;
  16337. len = subMeshes.length;
  16338. }
  16339. for (var index = 0; index < len; index++) {
  16340. var subMesh = subMeshes[index];
  16341. // Bounding test
  16342. if (len > 1 && !subMesh._checkCollision(collider))
  16343. continue;
  16344. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16345. }
  16346. return this;
  16347. };
  16348. AbstractMesh.prototype._checkCollision = function (collider) {
  16349. // Bounding box test
  16350. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16351. return this;
  16352. // Transformation matrix
  16353. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16354. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16355. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16356. return this;
  16357. };
  16358. // Picking
  16359. AbstractMesh.prototype._generatePointsArray = function () {
  16360. return false;
  16361. };
  16362. /**
  16363. * Checks if the passed Ray intersects with the mesh.
  16364. * Returns an object PickingInfo.
  16365. */
  16366. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16367. var pickingInfo = new BABYLON.PickingInfo();
  16368. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16369. return pickingInfo;
  16370. }
  16371. if (!this._generatePointsArray()) {
  16372. return pickingInfo;
  16373. }
  16374. var intersectInfo = null;
  16375. // Octrees
  16376. var subMeshes;
  16377. var len;
  16378. if (this._submeshesOctree && this.useOctreeForPicking) {
  16379. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16380. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16381. len = intersections.length;
  16382. subMeshes = intersections.data;
  16383. }
  16384. else {
  16385. subMeshes = this.subMeshes;
  16386. len = subMeshes.length;
  16387. }
  16388. for (var index = 0; index < len; index++) {
  16389. var subMesh = subMeshes[index];
  16390. // Bounding test
  16391. if (len > 1 && !subMesh.canIntersects(ray))
  16392. continue;
  16393. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16394. if (currentIntersectInfo) {
  16395. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16396. intersectInfo = currentIntersectInfo;
  16397. intersectInfo.subMeshId = index;
  16398. if (fastCheck) {
  16399. break;
  16400. }
  16401. }
  16402. }
  16403. }
  16404. if (intersectInfo) {
  16405. // Get picked point
  16406. var world = this.getWorldMatrix();
  16407. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16408. var direction = ray.direction.clone();
  16409. direction = direction.scale(intersectInfo.distance);
  16410. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16411. var pickedPoint = worldOrigin.add(worldDirection);
  16412. // Return result
  16413. pickingInfo.hit = true;
  16414. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16415. pickingInfo.pickedPoint = pickedPoint;
  16416. pickingInfo.pickedMesh = this;
  16417. pickingInfo.bu = intersectInfo.bu || 0;
  16418. pickingInfo.bv = intersectInfo.bv || 0;
  16419. pickingInfo.faceId = intersectInfo.faceId;
  16420. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16421. return pickingInfo;
  16422. }
  16423. return pickingInfo;
  16424. };
  16425. /**
  16426. * Clones the mesh, used by the class Mesh.
  16427. * Just returns `null` for an AbstractMesh.
  16428. */
  16429. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16430. return null;
  16431. };
  16432. /**
  16433. * Disposes all the mesh submeshes.
  16434. * Returns the AbstractMesh.
  16435. */
  16436. AbstractMesh.prototype.releaseSubMeshes = function () {
  16437. if (this.subMeshes) {
  16438. while (this.subMeshes.length) {
  16439. this.subMeshes[0].dispose();
  16440. }
  16441. }
  16442. else {
  16443. this.subMeshes = new Array();
  16444. }
  16445. return this;
  16446. };
  16447. /**
  16448. * Disposes the AbstractMesh.
  16449. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16450. * Returns nothing.
  16451. */
  16452. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16453. var _this = this;
  16454. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16455. var index;
  16456. // Action manager
  16457. if (this.actionManager !== undefined && this.actionManager !== null) {
  16458. this.actionManager.dispose();
  16459. this.actionManager = null;
  16460. }
  16461. // Skeleton
  16462. this.skeleton = null;
  16463. // Physics
  16464. if (this.physicsImpostor) {
  16465. this.physicsImpostor.dispose();
  16466. }
  16467. // Intersections in progress
  16468. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16469. var other = this._intersectionsInProgress[index];
  16470. var pos = other._intersectionsInProgress.indexOf(this);
  16471. other._intersectionsInProgress.splice(pos, 1);
  16472. }
  16473. this._intersectionsInProgress = [];
  16474. // Lights
  16475. var lights = this.getScene().lights;
  16476. lights.forEach(function (light) {
  16477. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16478. if (meshIndex !== -1) {
  16479. light.includedOnlyMeshes.splice(meshIndex, 1);
  16480. }
  16481. meshIndex = light.excludedMeshes.indexOf(_this);
  16482. if (meshIndex !== -1) {
  16483. light.excludedMeshes.splice(meshIndex, 1);
  16484. }
  16485. // Shadow generators
  16486. var generator = light.getShadowGenerator();
  16487. if (generator) {
  16488. var shadowMap = generator.getShadowMap();
  16489. if (shadowMap && shadowMap.renderList) {
  16490. meshIndex = shadowMap.renderList.indexOf(_this);
  16491. if (meshIndex !== -1) {
  16492. shadowMap.renderList.splice(meshIndex, 1);
  16493. }
  16494. }
  16495. }
  16496. });
  16497. // Edges
  16498. if (this._edgesRenderer) {
  16499. this._edgesRenderer.dispose();
  16500. this._edgesRenderer = null;
  16501. }
  16502. // SubMeshes
  16503. if (this.getClassName() !== "InstancedMesh") {
  16504. this.releaseSubMeshes();
  16505. }
  16506. // Octree
  16507. var sceneOctree = this.getScene().selectionOctree;
  16508. if (sceneOctree !== undefined && sceneOctree !== null) {
  16509. var index = sceneOctree.dynamicContent.indexOf(this);
  16510. if (index !== -1) {
  16511. sceneOctree.dynamicContent.splice(index, 1);
  16512. }
  16513. }
  16514. // Query
  16515. var engine = this.getScene().getEngine();
  16516. if (this._occlusionQuery) {
  16517. this._isOcclusionQueryInProgress = false;
  16518. engine.deleteQuery(this._occlusionQuery);
  16519. this._occlusionQuery = null;
  16520. }
  16521. // Engine
  16522. engine.wipeCaches();
  16523. // Remove from scene
  16524. this.getScene().removeMesh(this);
  16525. if (disposeMaterialAndTextures) {
  16526. if (this.material) {
  16527. this.material.dispose(false, true);
  16528. }
  16529. }
  16530. if (!doNotRecurse) {
  16531. // Particles
  16532. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16533. if (this.getScene().particleSystems[index].emitter === this) {
  16534. this.getScene().particleSystems[index].dispose();
  16535. index--;
  16536. }
  16537. }
  16538. }
  16539. // facet data
  16540. if (this._facetDataEnabled) {
  16541. this.disableFacetData();
  16542. }
  16543. this.onAfterWorldMatrixUpdateObservable.clear();
  16544. this.onCollideObservable.clear();
  16545. this.onCollisionPositionChangeObservable.clear();
  16546. this._isDisposed = true;
  16547. _super.prototype.dispose.call(this, doNotRecurse);
  16548. };
  16549. /**
  16550. * Adds the passed mesh as a child to the current mesh.
  16551. * Returns the AbstractMesh.
  16552. */
  16553. AbstractMesh.prototype.addChild = function (mesh) {
  16554. mesh.setParent(this);
  16555. return this;
  16556. };
  16557. /**
  16558. * Removes the passed mesh from the current mesh children list.
  16559. * Returns the AbstractMesh.
  16560. */
  16561. AbstractMesh.prototype.removeChild = function (mesh) {
  16562. mesh.setParent(null);
  16563. return this;
  16564. };
  16565. // Facet data
  16566. /**
  16567. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16568. * Returns the AbstractMesh.
  16569. */
  16570. AbstractMesh.prototype._initFacetData = function () {
  16571. if (!this._facetNormals) {
  16572. this._facetNormals = new Array();
  16573. }
  16574. if (!this._facetPositions) {
  16575. this._facetPositions = new Array();
  16576. }
  16577. if (!this._facetPartitioning) {
  16578. this._facetPartitioning = new Array();
  16579. }
  16580. this._facetNb = (this.getIndices().length / 3) | 0;
  16581. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16582. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16583. for (var f = 0; f < this._facetNb; f++) {
  16584. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16585. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16586. }
  16587. this._facetDataEnabled = true;
  16588. return this;
  16589. };
  16590. /**
  16591. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16592. * This method can be called within the render loop.
  16593. * 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.
  16594. * Returns the AbstractMesh.
  16595. */
  16596. AbstractMesh.prototype.updateFacetData = function () {
  16597. if (!this._facetDataEnabled) {
  16598. this._initFacetData();
  16599. }
  16600. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16601. var indices = this.getIndices();
  16602. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16603. var bInfo = this.getBoundingInfo();
  16604. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16605. // init arrays, matrix and sort function on first call
  16606. this._facetDepthSortEnabled = true;
  16607. if (indices instanceof Uint16Array) {
  16608. this._depthSortedIndices = new Uint16Array(indices);
  16609. }
  16610. else if (indices instanceof Uint32Array) {
  16611. this._depthSortedIndices = new Uint32Array(indices);
  16612. }
  16613. else {
  16614. var needs32bits = false;
  16615. for (var i = 0; i < indices.length; i++) {
  16616. if (indices[i] > 65535) {
  16617. needs32bits = true;
  16618. break;
  16619. }
  16620. }
  16621. if (needs32bits) {
  16622. this._depthSortedIndices = new Uint32Array(indices);
  16623. }
  16624. else {
  16625. this._depthSortedIndices = new Uint16Array(indices);
  16626. }
  16627. }
  16628. this._facetDepthSortFunction = function (f1, f2) {
  16629. return (f2.sqDistance - f1.sqDistance);
  16630. };
  16631. if (!this._facetDepthSortFrom) {
  16632. var camera = this.getScene().activeCamera;
  16633. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16634. }
  16635. this._depthSortedFacets = [];
  16636. for (var f = 0; f < this._facetNb; f++) {
  16637. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16638. this._depthSortedFacets.push(depthSortedFacet);
  16639. }
  16640. this._invertedMatrix = BABYLON.Matrix.Identity();
  16641. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16642. }
  16643. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16644. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16645. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16646. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16647. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16648. this._subDiv.max = this._partitioningSubdivisions;
  16649. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16650. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16651. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16652. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16653. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16654. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16655. // set the parameters for ComputeNormals()
  16656. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16657. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16658. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16659. this._facetParameters.bInfo = bInfo;
  16660. this._facetParameters.bbSize = this._bbSize;
  16661. this._facetParameters.subDiv = this._subDiv;
  16662. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16663. this._facetParameters.depthSort = this._facetDepthSort;
  16664. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16665. this.computeWorldMatrix(true);
  16666. this._worldMatrix.invertToRef(this._invertedMatrix);
  16667. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16668. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16669. }
  16670. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16671. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16672. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16673. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16674. var l = (this._depthSortedIndices.length / 3) | 0;
  16675. for (var f = 0; f < l; f++) {
  16676. var sind = this._depthSortedFacets[f].ind;
  16677. this._depthSortedIndices[f * 3] = indices[sind];
  16678. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16679. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16680. }
  16681. this.updateIndices(this._depthSortedIndices);
  16682. }
  16683. return this;
  16684. };
  16685. /**
  16686. * Returns the facetLocalNormals array.
  16687. * The normals are expressed in the mesh local space.
  16688. */
  16689. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16690. if (!this._facetNormals) {
  16691. this.updateFacetData();
  16692. }
  16693. return this._facetNormals;
  16694. };
  16695. /**
  16696. * Returns the facetLocalPositions array.
  16697. * The facet positions are expressed in the mesh local space.
  16698. */
  16699. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16700. if (!this._facetPositions) {
  16701. this.updateFacetData();
  16702. }
  16703. return this._facetPositions;
  16704. };
  16705. /**
  16706. * Returns the facetLocalPartioning array.
  16707. */
  16708. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16709. if (!this._facetPartitioning) {
  16710. this.updateFacetData();
  16711. }
  16712. return this._facetPartitioning;
  16713. };
  16714. /**
  16715. * Returns the i-th facet position in the world system.
  16716. * This method allocates a new Vector3 per call.
  16717. */
  16718. AbstractMesh.prototype.getFacetPosition = function (i) {
  16719. var pos = BABYLON.Vector3.Zero();
  16720. this.getFacetPositionToRef(i, pos);
  16721. return pos;
  16722. };
  16723. /**
  16724. * Sets the reference Vector3 with the i-th facet position in the world system.
  16725. * Returns the AbstractMesh.
  16726. */
  16727. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16728. var localPos = (this.getFacetLocalPositions())[i];
  16729. var world = this.getWorldMatrix();
  16730. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16731. return this;
  16732. };
  16733. /**
  16734. * Returns the i-th facet normal in the world system.
  16735. * This method allocates a new Vector3 per call.
  16736. */
  16737. AbstractMesh.prototype.getFacetNormal = function (i) {
  16738. var norm = BABYLON.Vector3.Zero();
  16739. this.getFacetNormalToRef(i, norm);
  16740. return norm;
  16741. };
  16742. /**
  16743. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16744. * Returns the AbstractMesh.
  16745. */
  16746. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16747. var localNorm = (this.getFacetLocalNormals())[i];
  16748. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16749. return this;
  16750. };
  16751. /**
  16752. * 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).
  16753. */
  16754. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16755. var bInfo = this.getBoundingInfo();
  16756. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16757. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16758. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16759. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16760. return null;
  16761. }
  16762. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16763. };
  16764. /**
  16765. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16766. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16767. * 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.
  16768. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16769. * 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.
  16770. */
  16771. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16772. if (checkFace === void 0) { checkFace = false; }
  16773. if (facing === void 0) { facing = true; }
  16774. var world = this.getWorldMatrix();
  16775. var invMat = BABYLON.Tmp.Matrix[5];
  16776. world.invertToRef(invMat);
  16777. var invVect = BABYLON.Tmp.Vector3[8];
  16778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16779. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16780. if (projected) {
  16781. // tranform the local computed projected vector to world coordinates
  16782. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16783. }
  16784. return closest;
  16785. };
  16786. /**
  16787. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16788. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16789. * 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.
  16790. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16791. * 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.
  16792. */
  16793. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16794. if (checkFace === void 0) { checkFace = false; }
  16795. if (facing === void 0) { facing = true; }
  16796. var closest = null;
  16797. var tmpx = 0.0;
  16798. var tmpy = 0.0;
  16799. var tmpz = 0.0;
  16800. var d = 0.0; // tmp dot facet normal * facet position
  16801. var t0 = 0.0;
  16802. var projx = 0.0;
  16803. var projy = 0.0;
  16804. var projz = 0.0;
  16805. // Get all the facets in the same partitioning block than (x, y, z)
  16806. var facetPositions = this.getFacetLocalPositions();
  16807. var facetNormals = this.getFacetLocalNormals();
  16808. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16809. if (!facetsInBlock) {
  16810. return null;
  16811. }
  16812. // Get the closest facet to (x, y, z)
  16813. var shortest = Number.MAX_VALUE; // init distance vars
  16814. var tmpDistance = shortest;
  16815. var fib; // current facet in the block
  16816. var norm; // current facet normal
  16817. var p0; // current facet barycenter position
  16818. // loop on all the facets in the current partitioning block
  16819. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16820. fib = facetsInBlock[idx];
  16821. norm = facetNormals[fib];
  16822. p0 = facetPositions[fib];
  16823. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16824. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16825. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16826. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16827. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16828. projx = x + norm.x * t0;
  16829. projy = y + norm.y * t0;
  16830. projz = z + norm.z * t0;
  16831. tmpx = projx - x;
  16832. tmpy = projy - y;
  16833. tmpz = projz - z;
  16834. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16835. if (tmpDistance < shortest) {
  16836. shortest = tmpDistance;
  16837. closest = fib;
  16838. if (projected) {
  16839. projected.x = projx;
  16840. projected.y = projy;
  16841. projected.z = projz;
  16842. }
  16843. }
  16844. }
  16845. }
  16846. return closest;
  16847. };
  16848. /**
  16849. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16850. */
  16851. AbstractMesh.prototype.getFacetDataParameters = function () {
  16852. return this._facetParameters;
  16853. };
  16854. /**
  16855. * Disables the feature FacetData and frees the related memory.
  16856. * Returns the AbstractMesh.
  16857. */
  16858. AbstractMesh.prototype.disableFacetData = function () {
  16859. if (this._facetDataEnabled) {
  16860. this._facetDataEnabled = false;
  16861. this._facetPositions = new Array();
  16862. this._facetNormals = new Array();
  16863. this._facetPartitioning = new Array();
  16864. this._facetParameters = null;
  16865. this._depthSortedIndices = new Uint32Array(0);
  16866. }
  16867. return this;
  16868. };
  16869. /**
  16870. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16871. * Returns the mesh.
  16872. */
  16873. AbstractMesh.prototype.updateIndices = function (indices) {
  16874. return this;
  16875. };
  16876. /**
  16877. * The mesh Geometry. Actually used by the Mesh object.
  16878. * Returns a blank geometry object.
  16879. */
  16880. /**
  16881. * Creates new normals data for the mesh.
  16882. * @param updatable.
  16883. */
  16884. AbstractMesh.prototype.createNormals = function (updatable) {
  16885. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16886. var indices = this.getIndices();
  16887. var normals;
  16888. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16889. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16890. }
  16891. else {
  16892. normals = [];
  16893. }
  16894. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16895. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16896. };
  16897. /**
  16898. * Align the mesh with a normal.
  16899. * Returns the mesh.
  16900. */
  16901. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16902. if (!upDirection) {
  16903. upDirection = BABYLON.Axis.Y;
  16904. }
  16905. var axisX = BABYLON.Tmp.Vector3[0];
  16906. var axisZ = BABYLON.Tmp.Vector3[1];
  16907. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16908. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16909. if (this.rotationQuaternion) {
  16910. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16911. }
  16912. else {
  16913. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16914. }
  16915. return this;
  16916. };
  16917. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16918. var engine = this.getEngine();
  16919. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16920. this._isOccluded = false;
  16921. return;
  16922. }
  16923. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16924. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16925. if (isOcclusionQueryAvailable) {
  16926. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16927. this._isOcclusionQueryInProgress = false;
  16928. this._occlusionInternalRetryCounter = 0;
  16929. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16930. }
  16931. else {
  16932. this._occlusionInternalRetryCounter++;
  16933. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16934. this._isOcclusionQueryInProgress = false;
  16935. this._occlusionInternalRetryCounter = 0;
  16936. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16937. // if strict continue the last state of the object.
  16938. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16939. }
  16940. else {
  16941. return;
  16942. }
  16943. }
  16944. }
  16945. var scene = this.getScene();
  16946. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16947. if (!this._occlusionQuery) {
  16948. this._occlusionQuery = engine.createQuery();
  16949. }
  16950. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16951. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16952. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16953. this._isOcclusionQueryInProgress = true;
  16954. };
  16955. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16956. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16957. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16958. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16959. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16960. return AbstractMesh;
  16961. }(BABYLON.TransformNode));
  16962. BABYLON.AbstractMesh = AbstractMesh;
  16963. })(BABYLON || (BABYLON = {}));
  16964. //# sourceMappingURL=babylon.abstractMesh.js.map
  16965. var BABYLON;
  16966. (function (BABYLON) {
  16967. var Light = /** @class */ (function (_super) {
  16968. __extends(Light, _super);
  16969. /**
  16970. * Creates a Light object in the scene.
  16971. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16972. */
  16973. function Light(name, scene) {
  16974. var _this = _super.call(this, name, scene) || this;
  16975. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16976. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16977. _this.intensity = 1.0;
  16978. _this.range = Number.MAX_VALUE;
  16979. /**
  16980. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16981. * of light.
  16982. */
  16983. _this._photometricScale = 1.0;
  16984. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16985. _this._radius = 0.00001;
  16986. _this.renderPriority = 0;
  16987. /**
  16988. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16989. * the current shadow generator.
  16990. */
  16991. _this.shadowEnabled = true;
  16992. _this._excludeWithLayerMask = 0;
  16993. _this._includeOnlyWithLayerMask = 0;
  16994. _this._lightmapMode = 0;
  16995. _this._excludedMeshesIds = new Array();
  16996. _this._includedOnlyMeshesIds = new Array();
  16997. _this.getScene().addLight(_this);
  16998. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  16999. _this._buildUniformLayout();
  17000. _this.includedOnlyMeshes = new Array();
  17001. _this.excludedMeshes = new Array();
  17002. _this._resyncMeshes();
  17003. return _this;
  17004. }
  17005. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17006. /**
  17007. * If every light affecting the material is in this lightmapMode,
  17008. * material.lightmapTexture adds or multiplies
  17009. * (depends on material.useLightmapAsShadowmap)
  17010. * after every other light calculations.
  17011. */
  17012. get: function () {
  17013. return Light._LIGHTMAP_DEFAULT;
  17014. },
  17015. enumerable: true,
  17016. configurable: true
  17017. });
  17018. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17019. /**
  17020. * material.lightmapTexture as only diffuse lighting from this light
  17021. * adds only specular lighting from this light
  17022. * adds dynamic shadows
  17023. */
  17024. get: function () {
  17025. return Light._LIGHTMAP_SPECULAR;
  17026. },
  17027. enumerable: true,
  17028. configurable: true
  17029. });
  17030. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17031. /**
  17032. * material.lightmapTexture as only lighting
  17033. * no light calculation from this light
  17034. * only adds dynamic shadows from this light
  17035. */
  17036. get: function () {
  17037. return Light._LIGHTMAP_SHADOWSONLY;
  17038. },
  17039. enumerable: true,
  17040. configurable: true
  17041. });
  17042. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17043. /**
  17044. * Each light type uses the default quantity according to its type:
  17045. * point/spot lights use luminous intensity
  17046. * directional lights use illuminance
  17047. */
  17048. get: function () {
  17049. return Light._INTENSITYMODE_AUTOMATIC;
  17050. },
  17051. enumerable: true,
  17052. configurable: true
  17053. });
  17054. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17055. /**
  17056. * lumen (lm)
  17057. */
  17058. get: function () {
  17059. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17060. },
  17061. enumerable: true,
  17062. configurable: true
  17063. });
  17064. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17065. /**
  17066. * candela (lm/sr)
  17067. */
  17068. get: function () {
  17069. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17075. /**
  17076. * lux (lm/m^2)
  17077. */
  17078. get: function () {
  17079. return Light._INTENSITYMODE_ILLUMINANCE;
  17080. },
  17081. enumerable: true,
  17082. configurable: true
  17083. });
  17084. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17085. /**
  17086. * nit (cd/m^2)
  17087. */
  17088. get: function () {
  17089. return Light._INTENSITYMODE_LUMINANCE;
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17095. /**
  17096. * Light type const id of the point light.
  17097. */
  17098. get: function () {
  17099. return Light._LIGHTTYPEID_POINTLIGHT;
  17100. },
  17101. enumerable: true,
  17102. configurable: true
  17103. });
  17104. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17105. /**
  17106. * Light type const id of the directional light.
  17107. */
  17108. get: function () {
  17109. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17110. },
  17111. enumerable: true,
  17112. configurable: true
  17113. });
  17114. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17115. /**
  17116. * Light type const id of the spot light.
  17117. */
  17118. get: function () {
  17119. return Light._LIGHTTYPEID_SPOTLIGHT;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17125. /**
  17126. * Light type const id of the hemispheric light.
  17127. */
  17128. get: function () {
  17129. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17130. },
  17131. enumerable: true,
  17132. configurable: true
  17133. });
  17134. Object.defineProperty(Light.prototype, "intensityMode", {
  17135. /**
  17136. * Gets the photometric scale used to interpret the intensity.
  17137. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17138. */
  17139. get: function () {
  17140. return this._intensityMode;
  17141. },
  17142. /**
  17143. * Sets the photometric scale used to interpret the intensity.
  17144. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17145. */
  17146. set: function (value) {
  17147. this._intensityMode = value;
  17148. this._computePhotometricScale();
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. ;
  17154. ;
  17155. Object.defineProperty(Light.prototype, "radius", {
  17156. /**
  17157. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17158. */
  17159. get: function () {
  17160. return this._radius;
  17161. },
  17162. /**
  17163. * sets the light radius used by PBR Materials to simulate soft area lights.
  17164. */
  17165. set: function (value) {
  17166. this._radius = value;
  17167. this._computePhotometricScale();
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. ;
  17173. ;
  17174. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17175. get: function () {
  17176. return this._includedOnlyMeshes;
  17177. },
  17178. set: function (value) {
  17179. this._includedOnlyMeshes = value;
  17180. this._hookArrayForIncludedOnly(value);
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17186. get: function () {
  17187. return this._excludedMeshes;
  17188. },
  17189. set: function (value) {
  17190. this._excludedMeshes = value;
  17191. this._hookArrayForExcluded(value);
  17192. },
  17193. enumerable: true,
  17194. configurable: true
  17195. });
  17196. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17197. get: function () {
  17198. return this._excludeWithLayerMask;
  17199. },
  17200. set: function (value) {
  17201. this._excludeWithLayerMask = value;
  17202. this._resyncMeshes();
  17203. },
  17204. enumerable: true,
  17205. configurable: true
  17206. });
  17207. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17208. get: function () {
  17209. return this._includeOnlyWithLayerMask;
  17210. },
  17211. set: function (value) {
  17212. this._includeOnlyWithLayerMask = value;
  17213. this._resyncMeshes();
  17214. },
  17215. enumerable: true,
  17216. configurable: true
  17217. });
  17218. Object.defineProperty(Light.prototype, "lightmapMode", {
  17219. get: function () {
  17220. return this._lightmapMode;
  17221. },
  17222. set: function (value) {
  17223. if (this._lightmapMode === value) {
  17224. return;
  17225. }
  17226. this._lightmapMode = value;
  17227. this._markMeshesAsLightDirty();
  17228. },
  17229. enumerable: true,
  17230. configurable: true
  17231. });
  17232. Light.prototype._buildUniformLayout = function () {
  17233. // Overridden
  17234. };
  17235. /**
  17236. * Returns the string "Light".
  17237. */
  17238. Light.prototype.getClassName = function () {
  17239. return "Light";
  17240. };
  17241. /**
  17242. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17243. */
  17244. Light.prototype.toString = function (fullDetails) {
  17245. var ret = "Name: " + this.name;
  17246. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17247. if (this.animations) {
  17248. for (var i = 0; i < this.animations.length; i++) {
  17249. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17250. }
  17251. }
  17252. if (fullDetails) {
  17253. }
  17254. return ret;
  17255. };
  17256. /**
  17257. * Set the enabled state of this node.
  17258. * @param {boolean} value - the new enabled state
  17259. * @see isEnabled
  17260. */
  17261. Light.prototype.setEnabled = function (value) {
  17262. _super.prototype.setEnabled.call(this, value);
  17263. this._resyncMeshes();
  17264. };
  17265. /**
  17266. * Returns the Light associated shadow generator.
  17267. */
  17268. Light.prototype.getShadowGenerator = function () {
  17269. return this._shadowGenerator;
  17270. };
  17271. /**
  17272. * Returns a Vector3, the absolute light position in the World.
  17273. */
  17274. Light.prototype.getAbsolutePosition = function () {
  17275. return BABYLON.Vector3.Zero();
  17276. };
  17277. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17278. };
  17279. Light.prototype._getWorldMatrix = function () {
  17280. return BABYLON.Matrix.Identity();
  17281. };
  17282. /**
  17283. * Boolean : True if the light will affect the passed mesh.
  17284. */
  17285. Light.prototype.canAffectMesh = function (mesh) {
  17286. if (!mesh) {
  17287. return true;
  17288. }
  17289. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17290. return false;
  17291. }
  17292. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17293. return false;
  17294. }
  17295. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17296. return false;
  17297. }
  17298. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17299. return false;
  17300. }
  17301. return true;
  17302. };
  17303. /**
  17304. * Returns the light World matrix.
  17305. */
  17306. Light.prototype.getWorldMatrix = function () {
  17307. this._currentRenderId = this.getScene().getRenderId();
  17308. var worldMatrix = this._getWorldMatrix();
  17309. if (this.parent && this.parent.getWorldMatrix) {
  17310. if (!this._parentedWorldMatrix) {
  17311. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17312. }
  17313. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17314. this._markSyncedWithParent();
  17315. return this._parentedWorldMatrix;
  17316. }
  17317. return worldMatrix;
  17318. };
  17319. /**
  17320. * Sort function to order lights for rendering.
  17321. * @param a First Light object to compare to second.
  17322. * @param b Second Light object to compare first.
  17323. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17324. */
  17325. Light.compareLightsPriority = function (a, b) {
  17326. //shadow-casting lights have priority over non-shadow-casting lights
  17327. //the renderPrioirty is a secondary sort criterion
  17328. if (a.shadowEnabled !== b.shadowEnabled) {
  17329. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17330. }
  17331. return b.renderPriority - a.renderPriority;
  17332. };
  17333. /**
  17334. * Disposes the light.
  17335. */
  17336. Light.prototype.dispose = function () {
  17337. if (this._shadowGenerator) {
  17338. this._shadowGenerator.dispose();
  17339. this._shadowGenerator = null;
  17340. }
  17341. // Animations
  17342. this.getScene().stopAnimation(this);
  17343. this._uniformBuffer.dispose();
  17344. // Remove from scene
  17345. this.getScene().removeLight(this);
  17346. _super.prototype.dispose.call(this);
  17347. };
  17348. /**
  17349. * Returns the light type ID (integer).
  17350. */
  17351. Light.prototype.getTypeID = function () {
  17352. return 0;
  17353. };
  17354. /**
  17355. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17356. */
  17357. Light.prototype.getScaledIntensity = function () {
  17358. return this._photometricScale * this.intensity;
  17359. };
  17360. /**
  17361. * Returns a new Light object, named "name", from the current one.
  17362. */
  17363. Light.prototype.clone = function (name) {
  17364. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17365. if (!constructor) {
  17366. return null;
  17367. }
  17368. return BABYLON.SerializationHelper.Clone(constructor, this);
  17369. };
  17370. /**
  17371. * Serializes the current light into a Serialization object.
  17372. * Returns the serialized object.
  17373. */
  17374. Light.prototype.serialize = function () {
  17375. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17376. // Type
  17377. serializationObject.type = this.getTypeID();
  17378. // Parent
  17379. if (this.parent) {
  17380. serializationObject.parentId = this.parent.id;
  17381. }
  17382. // Inclusion / exclusions
  17383. if (this.excludedMeshes.length > 0) {
  17384. serializationObject.excludedMeshesIds = [];
  17385. this.excludedMeshes.forEach(function (mesh) {
  17386. serializationObject.excludedMeshesIds.push(mesh.id);
  17387. });
  17388. }
  17389. if (this.includedOnlyMeshes.length > 0) {
  17390. serializationObject.includedOnlyMeshesIds = [];
  17391. this.includedOnlyMeshes.forEach(function (mesh) {
  17392. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17393. });
  17394. }
  17395. // Animations
  17396. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17397. serializationObject.ranges = this.serializeAnimationRanges();
  17398. return serializationObject;
  17399. };
  17400. /**
  17401. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17402. * This new light is named "name" and added to the passed scene.
  17403. */
  17404. Light.GetConstructorFromName = function (type, name, scene) {
  17405. switch (type) {
  17406. case 0:
  17407. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17408. case 1:
  17409. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17410. case 2:
  17411. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17412. case 3:
  17413. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17414. }
  17415. return null;
  17416. };
  17417. /**
  17418. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17419. */
  17420. Light.Parse = function (parsedLight, scene) {
  17421. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17422. if (!constructor) {
  17423. return null;
  17424. }
  17425. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17426. // Inclusion / exclusions
  17427. if (parsedLight.excludedMeshesIds) {
  17428. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17429. }
  17430. if (parsedLight.includedOnlyMeshesIds) {
  17431. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17432. }
  17433. // Parent
  17434. if (parsedLight.parentId) {
  17435. light._waitingParentId = parsedLight.parentId;
  17436. }
  17437. // Animations
  17438. if (parsedLight.animations) {
  17439. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17440. var parsedAnimation = parsedLight.animations[animationIndex];
  17441. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17442. }
  17443. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17444. }
  17445. if (parsedLight.autoAnimate) {
  17446. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17447. }
  17448. return light;
  17449. };
  17450. Light.prototype._hookArrayForExcluded = function (array) {
  17451. var _this = this;
  17452. var oldPush = array.push;
  17453. array.push = function () {
  17454. var items = [];
  17455. for (var _i = 0; _i < arguments.length; _i++) {
  17456. items[_i] = arguments[_i];
  17457. }
  17458. var result = oldPush.apply(array, items);
  17459. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17460. var item = items_1[_a];
  17461. item._resyncLighSource(_this);
  17462. }
  17463. return result;
  17464. };
  17465. var oldSplice = array.splice;
  17466. array.splice = function (index, deleteCount) {
  17467. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17468. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17469. var item = deleted_1[_i];
  17470. item._resyncLighSource(_this);
  17471. }
  17472. return deleted;
  17473. };
  17474. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17475. var item = array_1[_i];
  17476. item._resyncLighSource(this);
  17477. }
  17478. };
  17479. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17480. var _this = this;
  17481. var oldPush = array.push;
  17482. array.push = function () {
  17483. var items = [];
  17484. for (var _i = 0; _i < arguments.length; _i++) {
  17485. items[_i] = arguments[_i];
  17486. }
  17487. var result = oldPush.apply(array, items);
  17488. _this._resyncMeshes();
  17489. return result;
  17490. };
  17491. var oldSplice = array.splice;
  17492. array.splice = function (index, deleteCount) {
  17493. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17494. _this._resyncMeshes();
  17495. return deleted;
  17496. };
  17497. this._resyncMeshes();
  17498. };
  17499. Light.prototype._resyncMeshes = function () {
  17500. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17501. var mesh = _a[_i];
  17502. mesh._resyncLighSource(this);
  17503. }
  17504. };
  17505. Light.prototype._markMeshesAsLightDirty = function () {
  17506. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17507. var mesh = _a[_i];
  17508. if (mesh._lightSources.indexOf(this) !== -1) {
  17509. mesh._markSubMeshesAsLightDirty();
  17510. }
  17511. }
  17512. };
  17513. /**
  17514. * Recomputes the cached photometric scale if needed.
  17515. */
  17516. Light.prototype._computePhotometricScale = function () {
  17517. this._photometricScale = this._getPhotometricScale();
  17518. this.getScene().resetCachedMaterial();
  17519. };
  17520. /**
  17521. * Returns the Photometric Scale according to the light type and intensity mode.
  17522. */
  17523. Light.prototype._getPhotometricScale = function () {
  17524. var photometricScale = 0.0;
  17525. var lightTypeID = this.getTypeID();
  17526. //get photometric mode
  17527. var photometricMode = this.intensityMode;
  17528. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17529. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17530. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17531. }
  17532. else {
  17533. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17534. }
  17535. }
  17536. //compute photometric scale
  17537. switch (lightTypeID) {
  17538. case Light.LIGHTTYPEID_POINTLIGHT:
  17539. case Light.LIGHTTYPEID_SPOTLIGHT:
  17540. switch (photometricMode) {
  17541. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17542. photometricScale = 1.0 / (4.0 * Math.PI);
  17543. break;
  17544. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17545. photometricScale = 1.0;
  17546. break;
  17547. case Light.INTENSITYMODE_LUMINANCE:
  17548. photometricScale = this.radius * this.radius;
  17549. break;
  17550. }
  17551. break;
  17552. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17553. switch (photometricMode) {
  17554. case Light.INTENSITYMODE_ILLUMINANCE:
  17555. photometricScale = 1.0;
  17556. break;
  17557. case Light.INTENSITYMODE_LUMINANCE:
  17558. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17559. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17560. var apexAngleRadians = this.radius;
  17561. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17562. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17563. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17564. photometricScale = solidAngle;
  17565. break;
  17566. }
  17567. break;
  17568. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17569. // No fall off in hemisperic light.
  17570. photometricScale = 1.0;
  17571. break;
  17572. }
  17573. return photometricScale;
  17574. };
  17575. Light.prototype._reorderLightsInScene = function () {
  17576. var scene = this.getScene();
  17577. if (this._renderPriority != 0) {
  17578. scene.requireLightSorting = true;
  17579. }
  17580. this.getScene().sortLightsByPriority();
  17581. };
  17582. //lightmapMode Consts
  17583. Light._LIGHTMAP_DEFAULT = 0;
  17584. Light._LIGHTMAP_SPECULAR = 1;
  17585. Light._LIGHTMAP_SHADOWSONLY = 2;
  17586. // Intensity Mode Consts
  17587. Light._INTENSITYMODE_AUTOMATIC = 0;
  17588. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17589. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17590. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17591. Light._INTENSITYMODE_LUMINANCE = 4;
  17592. // Light types ids const.
  17593. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17594. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17595. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17596. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17597. __decorate([
  17598. BABYLON.serializeAsColor3()
  17599. ], Light.prototype, "diffuse", void 0);
  17600. __decorate([
  17601. BABYLON.serializeAsColor3()
  17602. ], Light.prototype, "specular", void 0);
  17603. __decorate([
  17604. BABYLON.serialize()
  17605. ], Light.prototype, "intensity", void 0);
  17606. __decorate([
  17607. BABYLON.serialize()
  17608. ], Light.prototype, "range", void 0);
  17609. __decorate([
  17610. BABYLON.serialize()
  17611. ], Light.prototype, "intensityMode", null);
  17612. __decorate([
  17613. BABYLON.serialize()
  17614. ], Light.prototype, "radius", null);
  17615. __decorate([
  17616. BABYLON.serialize()
  17617. ], Light.prototype, "_renderPriority", void 0);
  17618. __decorate([
  17619. BABYLON.expandToProperty("_reorderLightsInScene")
  17620. ], Light.prototype, "renderPriority", void 0);
  17621. __decorate([
  17622. BABYLON.serialize()
  17623. ], Light.prototype, "shadowEnabled", void 0);
  17624. __decorate([
  17625. BABYLON.serialize("excludeWithLayerMask")
  17626. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17627. __decorate([
  17628. BABYLON.serialize("includeOnlyWithLayerMask")
  17629. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17630. __decorate([
  17631. BABYLON.serialize("lightmapMode")
  17632. ], Light.prototype, "_lightmapMode", void 0);
  17633. return Light;
  17634. }(BABYLON.Node));
  17635. BABYLON.Light = Light;
  17636. })(BABYLON || (BABYLON = {}));
  17637. //# sourceMappingURL=babylon.light.js.map
  17638. var BABYLON;
  17639. (function (BABYLON) {
  17640. var Camera = /** @class */ (function (_super) {
  17641. __extends(Camera, _super);
  17642. function Camera(name, position, scene) {
  17643. var _this = _super.call(this, name, scene) || this;
  17644. _this.upVector = BABYLON.Vector3.Up();
  17645. _this.orthoLeft = null;
  17646. _this.orthoRight = null;
  17647. _this.orthoBottom = null;
  17648. _this.orthoTop = null;
  17649. /**
  17650. * default : 0.8
  17651. * FOV is set in Radians.
  17652. */
  17653. _this.fov = 0.8;
  17654. _this.minZ = 1;
  17655. _this.maxZ = 10000.0;
  17656. _this.inertia = 0.9;
  17657. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17658. _this.isIntermediate = false;
  17659. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17660. /**
  17661. * Restricts the camera to viewing objects with the same layerMask.
  17662. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17663. */
  17664. _this.layerMask = 0x0FFFFFFF;
  17665. /**
  17666. * default : FOVMODE_VERTICAL_FIXED
  17667. * fovMode sets the camera frustum bounds to the viewport bounds.
  17668. */
  17669. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17670. // Camera rig members
  17671. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17672. _this._rigCameras = new Array();
  17673. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17674. _this._skipRendering = false;
  17675. _this.customRenderTargets = new Array();
  17676. // Observables
  17677. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17678. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17679. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17680. _this.onRestoreStateObservable = new BABYLON.Observable();
  17681. // Cache
  17682. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17683. _this._projectionMatrix = new BABYLON.Matrix();
  17684. _this._doNotComputeProjectionMatrix = false;
  17685. _this._postProcesses = new Array();
  17686. _this._transformMatrix = BABYLON.Matrix.Zero();
  17687. _this._activeMeshes = new BABYLON.SmartArray(256);
  17688. _this._globalPosition = BABYLON.Vector3.Zero();
  17689. _this._refreshFrustumPlanes = true;
  17690. _this.getScene().addCamera(_this);
  17691. if (!_this.getScene().activeCamera) {
  17692. _this.getScene().activeCamera = _this;
  17693. }
  17694. _this.position = position;
  17695. return _this;
  17696. }
  17697. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17698. get: function () {
  17699. return Camera._PERSPECTIVE_CAMERA;
  17700. },
  17701. enumerable: true,
  17702. configurable: true
  17703. });
  17704. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17705. get: function () {
  17706. return Camera._ORTHOGRAPHIC_CAMERA;
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17712. /**
  17713. * This is the default FOV mode for perspective cameras.
  17714. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17715. *
  17716. */
  17717. get: function () {
  17718. return Camera._FOVMODE_VERTICAL_FIXED;
  17719. },
  17720. enumerable: true,
  17721. configurable: true
  17722. });
  17723. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17724. /**
  17725. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17726. *
  17727. */
  17728. get: function () {
  17729. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17730. },
  17731. enumerable: true,
  17732. configurable: true
  17733. });
  17734. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17735. get: function () {
  17736. return Camera._RIG_MODE_NONE;
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17742. get: function () {
  17743. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17744. },
  17745. enumerable: true,
  17746. configurable: true
  17747. });
  17748. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17749. get: function () {
  17750. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17756. get: function () {
  17757. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17763. get: function () {
  17764. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17770. get: function () {
  17771. return Camera._RIG_MODE_VR;
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17777. get: function () {
  17778. return Camera._RIG_MODE_WEBVR;
  17779. },
  17780. enumerable: true,
  17781. configurable: true
  17782. });
  17783. /**
  17784. * Store current camera state (fov, position, etc..)
  17785. */
  17786. Camera.prototype.storeState = function () {
  17787. this._stateStored = true;
  17788. this._storedFov = this.fov;
  17789. return this;
  17790. };
  17791. /**
  17792. * Restores the camera state values if it has been stored. You must call storeState() first
  17793. */
  17794. Camera.prototype._restoreStateValues = function () {
  17795. if (!this._stateStored) {
  17796. return false;
  17797. }
  17798. this.fov = this._storedFov;
  17799. return true;
  17800. };
  17801. /**
  17802. * Restored camera state. You must call storeState() first
  17803. */
  17804. Camera.prototype.restoreState = function () {
  17805. if (this._restoreStateValues()) {
  17806. this.onRestoreStateObservable.notifyObservers(this);
  17807. return true;
  17808. }
  17809. return false;
  17810. };
  17811. Camera.prototype.getClassName = function () {
  17812. return "Camera";
  17813. };
  17814. /**
  17815. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17816. */
  17817. Camera.prototype.toString = function (fullDetails) {
  17818. var ret = "Name: " + this.name;
  17819. ret += ", type: " + this.getClassName();
  17820. if (this.animations) {
  17821. for (var i = 0; i < this.animations.length; i++) {
  17822. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17823. }
  17824. }
  17825. if (fullDetails) {
  17826. }
  17827. return ret;
  17828. };
  17829. Object.defineProperty(Camera.prototype, "globalPosition", {
  17830. get: function () {
  17831. return this._globalPosition;
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Camera.prototype.getActiveMeshes = function () {
  17837. return this._activeMeshes;
  17838. };
  17839. Camera.prototype.isActiveMesh = function (mesh) {
  17840. return (this._activeMeshes.indexOf(mesh) !== -1);
  17841. };
  17842. //Cache
  17843. Camera.prototype._initCache = function () {
  17844. _super.prototype._initCache.call(this);
  17845. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17846. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17847. this._cache.mode = undefined;
  17848. this._cache.minZ = undefined;
  17849. this._cache.maxZ = undefined;
  17850. this._cache.fov = undefined;
  17851. this._cache.fovMode = undefined;
  17852. this._cache.aspectRatio = undefined;
  17853. this._cache.orthoLeft = undefined;
  17854. this._cache.orthoRight = undefined;
  17855. this._cache.orthoBottom = undefined;
  17856. this._cache.orthoTop = undefined;
  17857. this._cache.renderWidth = undefined;
  17858. this._cache.renderHeight = undefined;
  17859. };
  17860. Camera.prototype._updateCache = function (ignoreParentClass) {
  17861. if (!ignoreParentClass) {
  17862. _super.prototype._updateCache.call(this);
  17863. }
  17864. this._cache.position.copyFrom(this.position);
  17865. this._cache.upVector.copyFrom(this.upVector);
  17866. };
  17867. // Synchronized
  17868. Camera.prototype._isSynchronized = function () {
  17869. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17870. };
  17871. Camera.prototype._isSynchronizedViewMatrix = function () {
  17872. if (!_super.prototype._isSynchronized.call(this))
  17873. return false;
  17874. return this._cache.position.equals(this.position)
  17875. && this._cache.upVector.equals(this.upVector)
  17876. && this.isSynchronizedWithParent();
  17877. };
  17878. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17879. var check = this._cache.mode === this.mode
  17880. && this._cache.minZ === this.minZ
  17881. && this._cache.maxZ === this.maxZ;
  17882. if (!check) {
  17883. return false;
  17884. }
  17885. var engine = this.getEngine();
  17886. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17887. check = this._cache.fov === this.fov
  17888. && this._cache.fovMode === this.fovMode
  17889. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17890. }
  17891. else {
  17892. check = this._cache.orthoLeft === this.orthoLeft
  17893. && this._cache.orthoRight === this.orthoRight
  17894. && this._cache.orthoBottom === this.orthoBottom
  17895. && this._cache.orthoTop === this.orthoTop
  17896. && this._cache.renderWidth === engine.getRenderWidth()
  17897. && this._cache.renderHeight === engine.getRenderHeight();
  17898. }
  17899. return check;
  17900. };
  17901. // Controls
  17902. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17903. };
  17904. Camera.prototype.detachControl = function (element) {
  17905. };
  17906. Camera.prototype.update = function () {
  17907. this._checkInputs();
  17908. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17909. this._updateRigCameras();
  17910. }
  17911. };
  17912. Camera.prototype._checkInputs = function () {
  17913. this.onAfterCheckInputsObservable.notifyObservers(this);
  17914. };
  17915. Object.defineProperty(Camera.prototype, "rigCameras", {
  17916. get: function () {
  17917. return this._rigCameras;
  17918. },
  17919. enumerable: true,
  17920. configurable: true
  17921. });
  17922. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17923. get: function () {
  17924. return this._rigPostProcess;
  17925. },
  17926. enumerable: true,
  17927. configurable: true
  17928. });
  17929. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17930. // invalidate framebuffer
  17931. if (this._postProcesses.length > 0) {
  17932. this._postProcesses[0].markTextureDirty();
  17933. }
  17934. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17935. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17936. var cam = this._rigCameras[i];
  17937. var rigPostProcess = cam._rigPostProcess;
  17938. // for VR rig, there does not have to be a post process
  17939. if (rigPostProcess) {
  17940. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17941. if (isPass) {
  17942. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17943. cam.isIntermediate = this._postProcesses.length === 0;
  17944. }
  17945. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17946. rigPostProcess.markTextureDirty();
  17947. }
  17948. else {
  17949. cam._postProcesses = this._postProcesses.slice(0);
  17950. }
  17951. }
  17952. };
  17953. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17954. if (insertAt === void 0) { insertAt = null; }
  17955. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17956. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17957. return 0;
  17958. }
  17959. if (insertAt == null || insertAt < 0) {
  17960. this._postProcesses.push(postProcess);
  17961. }
  17962. else {
  17963. this._postProcesses.splice(insertAt, 0, postProcess);
  17964. }
  17965. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17966. return this._postProcesses.indexOf(postProcess);
  17967. };
  17968. Camera.prototype.detachPostProcess = function (postProcess) {
  17969. var idx = this._postProcesses.indexOf(postProcess);
  17970. if (idx !== -1) {
  17971. this._postProcesses.splice(idx, 1);
  17972. }
  17973. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17974. };
  17975. Camera.prototype.getWorldMatrix = function () {
  17976. if (!this._worldMatrix) {
  17977. this._worldMatrix = BABYLON.Matrix.Identity();
  17978. }
  17979. var viewMatrix = this.getViewMatrix();
  17980. viewMatrix.invertToRef(this._worldMatrix);
  17981. return this._worldMatrix;
  17982. };
  17983. Camera.prototype._getViewMatrix = function () {
  17984. return BABYLON.Matrix.Identity();
  17985. };
  17986. Camera.prototype.getViewMatrix = function (force) {
  17987. if (!force && this._isSynchronizedViewMatrix()) {
  17988. return this._computedViewMatrix;
  17989. }
  17990. this.updateCache();
  17991. this._computedViewMatrix = this._getViewMatrix();
  17992. this._currentRenderId = this.getScene().getRenderId();
  17993. this._refreshFrustumPlanes = true;
  17994. if (!this.parent || !this.parent.getWorldMatrix) {
  17995. this._globalPosition.copyFrom(this.position);
  17996. }
  17997. else {
  17998. if (!this._worldMatrix) {
  17999. this._worldMatrix = BABYLON.Matrix.Identity();
  18000. }
  18001. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18002. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18003. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18004. this._computedViewMatrix.invert();
  18005. this._markSyncedWithParent();
  18006. }
  18007. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18008. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18009. }
  18010. this.onViewMatrixChangedObservable.notifyObservers(this);
  18011. return this._computedViewMatrix;
  18012. };
  18013. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18014. this._doNotComputeProjectionMatrix = true;
  18015. if (projection !== undefined) {
  18016. this._projectionMatrix = projection;
  18017. }
  18018. };
  18019. ;
  18020. Camera.prototype.unfreezeProjectionMatrix = function () {
  18021. this._doNotComputeProjectionMatrix = false;
  18022. };
  18023. ;
  18024. Camera.prototype.getProjectionMatrix = function (force) {
  18025. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18026. return this._projectionMatrix;
  18027. }
  18028. // Cache
  18029. this._cache.mode = this.mode;
  18030. this._cache.minZ = this.minZ;
  18031. this._cache.maxZ = this.maxZ;
  18032. // Matrix
  18033. this._refreshFrustumPlanes = true;
  18034. var engine = this.getEngine();
  18035. var scene = this.getScene();
  18036. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18037. this._cache.fov = this.fov;
  18038. this._cache.fovMode = this.fovMode;
  18039. this._cache.aspectRatio = engine.getAspectRatio(this);
  18040. if (this.minZ <= 0) {
  18041. this.minZ = 0.1;
  18042. }
  18043. if (scene.useRightHandedSystem) {
  18044. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18045. }
  18046. else {
  18047. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18048. }
  18049. }
  18050. else {
  18051. var halfWidth = engine.getRenderWidth() / 2.0;
  18052. var halfHeight = engine.getRenderHeight() / 2.0;
  18053. if (scene.useRightHandedSystem) {
  18054. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18055. }
  18056. else {
  18057. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18058. }
  18059. this._cache.orthoLeft = this.orthoLeft;
  18060. this._cache.orthoRight = this.orthoRight;
  18061. this._cache.orthoBottom = this.orthoBottom;
  18062. this._cache.orthoTop = this.orthoTop;
  18063. this._cache.renderWidth = engine.getRenderWidth();
  18064. this._cache.renderHeight = engine.getRenderHeight();
  18065. }
  18066. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18067. return this._projectionMatrix;
  18068. };
  18069. Camera.prototype.getTranformationMatrix = function () {
  18070. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18071. return this._transformMatrix;
  18072. };
  18073. Camera.prototype.updateFrustumPlanes = function () {
  18074. if (!this._refreshFrustumPlanes) {
  18075. return;
  18076. }
  18077. this.getTranformationMatrix();
  18078. if (!this._frustumPlanes) {
  18079. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18080. }
  18081. else {
  18082. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18083. }
  18084. this._refreshFrustumPlanes = false;
  18085. };
  18086. Camera.prototype.isInFrustum = function (target) {
  18087. this.updateFrustumPlanes();
  18088. return target.isInFrustum(this._frustumPlanes);
  18089. };
  18090. Camera.prototype.isCompletelyInFrustum = function (target) {
  18091. this.updateFrustumPlanes();
  18092. return target.isCompletelyInFrustum(this._frustumPlanes);
  18093. };
  18094. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18095. if (length === void 0) { length = 100; }
  18096. if (!transform) {
  18097. transform = this.getWorldMatrix();
  18098. }
  18099. if (!origin) {
  18100. origin = this.position;
  18101. }
  18102. var forward = new BABYLON.Vector3(0, 0, 1);
  18103. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18104. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18105. return new BABYLON.Ray(origin, direction, length);
  18106. };
  18107. Camera.prototype.dispose = function () {
  18108. // Observables
  18109. this.onViewMatrixChangedObservable.clear();
  18110. this.onProjectionMatrixChangedObservable.clear();
  18111. this.onAfterCheckInputsObservable.clear();
  18112. this.onRestoreStateObservable.clear();
  18113. // Inputs
  18114. if (this.inputs) {
  18115. this.inputs.clear();
  18116. }
  18117. // Animations
  18118. this.getScene().stopAnimation(this);
  18119. // Remove from scene
  18120. this.getScene().removeCamera(this);
  18121. while (this._rigCameras.length > 0) {
  18122. var camera = this._rigCameras.pop();
  18123. if (camera) {
  18124. camera.dispose();
  18125. }
  18126. }
  18127. // Postprocesses
  18128. if (this._rigPostProcess) {
  18129. this._rigPostProcess.dispose(this);
  18130. this._rigPostProcess = null;
  18131. this._postProcesses = [];
  18132. }
  18133. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18134. this._rigPostProcess = null;
  18135. this._postProcesses = [];
  18136. }
  18137. else {
  18138. var i = this._postProcesses.length;
  18139. while (--i >= 0) {
  18140. this._postProcesses[i].dispose(this);
  18141. }
  18142. }
  18143. // Render targets
  18144. var i = this.customRenderTargets.length;
  18145. while (--i >= 0) {
  18146. this.customRenderTargets[i].dispose();
  18147. }
  18148. this.customRenderTargets = [];
  18149. // Active Meshes
  18150. this._activeMeshes.dispose();
  18151. _super.prototype.dispose.call(this);
  18152. };
  18153. Object.defineProperty(Camera.prototype, "leftCamera", {
  18154. // ---- Camera rigs section ----
  18155. get: function () {
  18156. if (this._rigCameras.length < 1) {
  18157. return null;
  18158. }
  18159. return this._rigCameras[0];
  18160. },
  18161. enumerable: true,
  18162. configurable: true
  18163. });
  18164. Object.defineProperty(Camera.prototype, "rightCamera", {
  18165. get: function () {
  18166. if (this._rigCameras.length < 2) {
  18167. return null;
  18168. }
  18169. return this._rigCameras[1];
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. Camera.prototype.getLeftTarget = function () {
  18175. if (this._rigCameras.length < 1) {
  18176. return null;
  18177. }
  18178. return this._rigCameras[0].getTarget();
  18179. };
  18180. Camera.prototype.getRightTarget = function () {
  18181. if (this._rigCameras.length < 2) {
  18182. return null;
  18183. }
  18184. return this._rigCameras[1].getTarget();
  18185. };
  18186. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18187. if (this.cameraRigMode === mode) {
  18188. return;
  18189. }
  18190. while (this._rigCameras.length > 0) {
  18191. var camera = this._rigCameras.pop();
  18192. if (camera) {
  18193. camera.dispose();
  18194. }
  18195. }
  18196. this.cameraRigMode = mode;
  18197. this._cameraRigParams = {};
  18198. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18199. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18200. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18201. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18202. // create the rig cameras, unless none
  18203. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18204. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18205. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18206. if (leftCamera && rightCamera) {
  18207. this._rigCameras.push(leftCamera);
  18208. this._rigCameras.push(rightCamera);
  18209. }
  18210. }
  18211. switch (this.cameraRigMode) {
  18212. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18213. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18214. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18215. break;
  18216. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18217. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18218. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18219. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18220. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18221. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18222. break;
  18223. case Camera.RIG_MODE_VR:
  18224. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18225. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18226. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18227. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18228. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18229. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18230. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18231. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18232. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18233. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18234. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18235. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18236. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18237. if (metrics.compensateDistortion) {
  18238. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18239. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18240. }
  18241. break;
  18242. case Camera.RIG_MODE_WEBVR:
  18243. if (rigParams.vrDisplay) {
  18244. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18245. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18246. //Left eye
  18247. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18248. this._rigCameras[0].setCameraRigParameter("left", true);
  18249. //leaving this for future reference
  18250. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18251. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18252. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18253. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18254. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18255. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18256. this._rigCameras[0].parent = this;
  18257. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18258. //Right eye
  18259. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18260. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18261. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18262. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18263. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18264. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18265. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18266. this._rigCameras[1].parent = this;
  18267. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18268. if (Camera.UseAlternateWebVRRendering) {
  18269. this._rigCameras[1]._skipRendering = true;
  18270. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18271. }
  18272. }
  18273. break;
  18274. }
  18275. this._cascadePostProcessesToRigCams();
  18276. this.update();
  18277. };
  18278. Camera.prototype._getVRProjectionMatrix = function () {
  18279. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18280. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18281. return this._projectionMatrix;
  18282. };
  18283. Camera.prototype._updateCameraRotationMatrix = function () {
  18284. //Here for WebVR
  18285. };
  18286. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18287. //Here for WebVR
  18288. };
  18289. /**
  18290. * This function MUST be overwritten by the different WebVR cameras available.
  18291. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18292. */
  18293. Camera.prototype._getWebVRProjectionMatrix = function () {
  18294. return BABYLON.Matrix.Identity();
  18295. };
  18296. /**
  18297. * This function MUST be overwritten by the different WebVR cameras available.
  18298. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18299. */
  18300. Camera.prototype._getWebVRViewMatrix = function () {
  18301. return BABYLON.Matrix.Identity();
  18302. };
  18303. Camera.prototype.setCameraRigParameter = function (name, value) {
  18304. if (!this._cameraRigParams) {
  18305. this._cameraRigParams = {};
  18306. }
  18307. this._cameraRigParams[name] = value;
  18308. //provisionnally:
  18309. if (name === "interaxialDistance") {
  18310. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18311. }
  18312. };
  18313. /**
  18314. * needs to be overridden by children so sub has required properties to be copied
  18315. */
  18316. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18317. return null;
  18318. };
  18319. /**
  18320. * May need to be overridden by children
  18321. */
  18322. Camera.prototype._updateRigCameras = function () {
  18323. for (var i = 0; i < this._rigCameras.length; i++) {
  18324. this._rigCameras[i].minZ = this.minZ;
  18325. this._rigCameras[i].maxZ = this.maxZ;
  18326. this._rigCameras[i].fov = this.fov;
  18327. }
  18328. // only update viewport when ANAGLYPH
  18329. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18330. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18331. }
  18332. };
  18333. Camera.prototype._setupInputs = function () {
  18334. };
  18335. Camera.prototype.serialize = function () {
  18336. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18337. // Type
  18338. serializationObject.type = this.getClassName();
  18339. // Parent
  18340. if (this.parent) {
  18341. serializationObject.parentId = this.parent.id;
  18342. }
  18343. if (this.inputs) {
  18344. this.inputs.serialize(serializationObject);
  18345. }
  18346. // Animations
  18347. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18348. serializationObject.ranges = this.serializeAnimationRanges();
  18349. return serializationObject;
  18350. };
  18351. Camera.prototype.clone = function (name) {
  18352. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18353. };
  18354. Camera.prototype.getDirection = function (localAxis) {
  18355. var result = BABYLON.Vector3.Zero();
  18356. this.getDirectionToRef(localAxis, result);
  18357. return result;
  18358. };
  18359. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18360. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18361. };
  18362. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18363. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18364. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18365. switch (type) {
  18366. case "ArcRotateCamera":
  18367. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18368. case "DeviceOrientationCamera":
  18369. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18370. case "FollowCamera":
  18371. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18372. case "ArcFollowCamera":
  18373. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18374. case "GamepadCamera":
  18375. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18376. case "TouchCamera":
  18377. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18378. case "VirtualJoysticksCamera":
  18379. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18380. case "WebVRFreeCamera":
  18381. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18382. case "WebVRGamepadCamera":
  18383. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18384. case "VRDeviceOrientationFreeCamera":
  18385. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18386. case "VRDeviceOrientationGamepadCamera":
  18387. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18388. case "AnaglyphArcRotateCamera":
  18389. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18390. case "AnaglyphFreeCamera":
  18391. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18392. case "AnaglyphGamepadCamera":
  18393. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18394. case "AnaglyphUniversalCamera":
  18395. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18396. case "StereoscopicArcRotateCamera":
  18397. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18398. case "StereoscopicFreeCamera":
  18399. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18400. case "StereoscopicGamepadCamera":
  18401. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18402. case "StereoscopicUniversalCamera":
  18403. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18404. case "FreeCamera":// Forcing Universal here
  18405. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18406. default:// Universal Camera is the default value
  18407. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18408. }
  18409. };
  18410. Camera.prototype.computeWorldMatrix = function () {
  18411. return this.getWorldMatrix();
  18412. };
  18413. Camera.Parse = function (parsedCamera, scene) {
  18414. var type = parsedCamera.type;
  18415. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18416. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18417. // Parent
  18418. if (parsedCamera.parentId) {
  18419. camera._waitingParentId = parsedCamera.parentId;
  18420. }
  18421. //If camera has an input manager, let it parse inputs settings
  18422. if (camera.inputs) {
  18423. camera.inputs.parse(parsedCamera);
  18424. camera._setupInputs();
  18425. }
  18426. if (camera.setPosition) {
  18427. camera.position.copyFromFloats(0, 0, 0);
  18428. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18429. }
  18430. // Target
  18431. if (parsedCamera.target) {
  18432. if (camera.setTarget) {
  18433. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18434. }
  18435. }
  18436. // Apply 3d rig, when found
  18437. if (parsedCamera.cameraRigMode) {
  18438. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18439. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18440. }
  18441. // Animations
  18442. if (parsedCamera.animations) {
  18443. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18444. var parsedAnimation = parsedCamera.animations[animationIndex];
  18445. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18446. }
  18447. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18448. }
  18449. if (parsedCamera.autoAnimate) {
  18450. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18451. }
  18452. return camera;
  18453. };
  18454. // Statics
  18455. Camera._PERSPECTIVE_CAMERA = 0;
  18456. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18457. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18458. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18459. Camera._RIG_MODE_NONE = 0;
  18460. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18461. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18462. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18463. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18464. Camera._RIG_MODE_VR = 20;
  18465. Camera._RIG_MODE_WEBVR = 21;
  18466. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18467. Camera.UseAlternateWebVRRendering = false;
  18468. __decorate([
  18469. BABYLON.serializeAsVector3()
  18470. ], Camera.prototype, "position", void 0);
  18471. __decorate([
  18472. BABYLON.serializeAsVector3()
  18473. ], Camera.prototype, "upVector", void 0);
  18474. __decorate([
  18475. BABYLON.serialize()
  18476. ], Camera.prototype, "orthoLeft", void 0);
  18477. __decorate([
  18478. BABYLON.serialize()
  18479. ], Camera.prototype, "orthoRight", void 0);
  18480. __decorate([
  18481. BABYLON.serialize()
  18482. ], Camera.prototype, "orthoBottom", void 0);
  18483. __decorate([
  18484. BABYLON.serialize()
  18485. ], Camera.prototype, "orthoTop", void 0);
  18486. __decorate([
  18487. BABYLON.serialize()
  18488. ], Camera.prototype, "fov", void 0);
  18489. __decorate([
  18490. BABYLON.serialize()
  18491. ], Camera.prototype, "minZ", void 0);
  18492. __decorate([
  18493. BABYLON.serialize()
  18494. ], Camera.prototype, "maxZ", void 0);
  18495. __decorate([
  18496. BABYLON.serialize()
  18497. ], Camera.prototype, "inertia", void 0);
  18498. __decorate([
  18499. BABYLON.serialize()
  18500. ], Camera.prototype, "mode", void 0);
  18501. __decorate([
  18502. BABYLON.serialize()
  18503. ], Camera.prototype, "layerMask", void 0);
  18504. __decorate([
  18505. BABYLON.serialize()
  18506. ], Camera.prototype, "fovMode", void 0);
  18507. __decorate([
  18508. BABYLON.serialize()
  18509. ], Camera.prototype, "cameraRigMode", void 0);
  18510. __decorate([
  18511. BABYLON.serialize()
  18512. ], Camera.prototype, "interaxialDistance", void 0);
  18513. __decorate([
  18514. BABYLON.serialize()
  18515. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18516. return Camera;
  18517. }(BABYLON.Node));
  18518. BABYLON.Camera = Camera;
  18519. })(BABYLON || (BABYLON = {}));
  18520. //# sourceMappingURL=babylon.camera.js.map
  18521. var BABYLON;
  18522. (function (BABYLON) {
  18523. var RenderingManager = /** @class */ (function () {
  18524. function RenderingManager(scene) {
  18525. this._renderingGroups = new Array();
  18526. this._autoClearDepthStencil = {};
  18527. this._customOpaqueSortCompareFn = {};
  18528. this._customAlphaTestSortCompareFn = {};
  18529. this._customTransparentSortCompareFn = {};
  18530. this._renderinGroupInfo = null;
  18531. this._scene = scene;
  18532. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18533. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18534. }
  18535. }
  18536. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18537. if (depth === void 0) { depth = true; }
  18538. if (stencil === void 0) { stencil = true; }
  18539. if (this._depthStencilBufferAlreadyCleaned) {
  18540. return;
  18541. }
  18542. this._scene.getEngine().clear(null, false, depth, stencil);
  18543. this._depthStencilBufferAlreadyCleaned = true;
  18544. };
  18545. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18546. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18547. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18548. var info = null;
  18549. if (observable) {
  18550. if (!this._renderinGroupInfo) {
  18551. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18552. }
  18553. info = this._renderinGroupInfo;
  18554. info.scene = this._scene;
  18555. info.camera = this._scene.activeCamera;
  18556. }
  18557. // Dispatch sprites
  18558. if (renderSprites) {
  18559. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18560. var manager = this._scene.spriteManagers[index];
  18561. this.dispatchSprites(manager);
  18562. }
  18563. }
  18564. // Render
  18565. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18566. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18567. var renderingGroup = this._renderingGroups[index];
  18568. if (!renderingGroup && !observable)
  18569. continue;
  18570. var renderingGroupMask = 0;
  18571. // Fire PRECLEAR stage
  18572. if (observable && info) {
  18573. renderingGroupMask = Math.pow(2, index);
  18574. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18575. info.renderingGroupId = index;
  18576. observable.notifyObservers(info, renderingGroupMask);
  18577. }
  18578. // Clear depth/stencil if needed
  18579. if (RenderingManager.AUTOCLEAR) {
  18580. var autoClear = this._autoClearDepthStencil[index];
  18581. if (autoClear && autoClear.autoClear) {
  18582. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18583. }
  18584. }
  18585. if (observable && info) {
  18586. // Fire PREOPAQUE stage
  18587. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18588. observable.notifyObservers(info, renderingGroupMask);
  18589. // Fire PRETRANSPARENT stage
  18590. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18591. observable.notifyObservers(info, renderingGroupMask);
  18592. }
  18593. if (renderingGroup)
  18594. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18595. // Fire POSTTRANSPARENT stage
  18596. if (observable && info) {
  18597. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18598. observable.notifyObservers(info, renderingGroupMask);
  18599. }
  18600. }
  18601. };
  18602. RenderingManager.prototype.reset = function () {
  18603. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18604. var renderingGroup = this._renderingGroups[index];
  18605. if (renderingGroup) {
  18606. renderingGroup.prepare();
  18607. }
  18608. }
  18609. };
  18610. RenderingManager.prototype.dispose = function () {
  18611. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18612. var renderingGroup = this._renderingGroups[index];
  18613. if (renderingGroup) {
  18614. renderingGroup.dispose();
  18615. }
  18616. }
  18617. this._renderingGroups.length = 0;
  18618. };
  18619. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18620. if (this._renderingGroups[renderingGroupId] === undefined) {
  18621. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18622. }
  18623. };
  18624. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18625. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18626. this._prepareRenderingGroup(renderingGroupId);
  18627. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18628. };
  18629. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18630. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18631. this._prepareRenderingGroup(renderingGroupId);
  18632. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18633. };
  18634. /**
  18635. * @param subMesh The submesh to dispatch
  18636. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18637. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18638. */
  18639. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18640. if (mesh === undefined) {
  18641. mesh = subMesh.getMesh();
  18642. }
  18643. var renderingGroupId = mesh.renderingGroupId || 0;
  18644. this._prepareRenderingGroup(renderingGroupId);
  18645. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18646. };
  18647. /**
  18648. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18649. * This allowed control for front to back rendering or reversly depending of the special needs.
  18650. *
  18651. * @param renderingGroupId The rendering group id corresponding to its index
  18652. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18653. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18654. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18655. */
  18656. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18657. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18658. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18659. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18660. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18661. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18662. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18663. if (this._renderingGroups[renderingGroupId]) {
  18664. var group = this._renderingGroups[renderingGroupId];
  18665. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18666. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18667. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18668. }
  18669. };
  18670. /**
  18671. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18672. *
  18673. * @param renderingGroupId The rendering group id corresponding to its index
  18674. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18675. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18676. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18677. */
  18678. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18679. if (depth === void 0) { depth = true; }
  18680. if (stencil === void 0) { stencil = true; }
  18681. this._autoClearDepthStencil[renderingGroupId] = {
  18682. autoClear: autoClearDepthStencil,
  18683. depth: depth,
  18684. stencil: stencil
  18685. };
  18686. };
  18687. /**
  18688. * The max id used for rendering groups (not included)
  18689. */
  18690. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18691. /**
  18692. * The min id used for rendering groups (included)
  18693. */
  18694. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18695. /**
  18696. * Used to globally prevent autoclearing scenes.
  18697. */
  18698. RenderingManager.AUTOCLEAR = true;
  18699. return RenderingManager;
  18700. }());
  18701. BABYLON.RenderingManager = RenderingManager;
  18702. })(BABYLON || (BABYLON = {}));
  18703. //# sourceMappingURL=babylon.renderingManager.js.map
  18704. var BABYLON;
  18705. (function (BABYLON) {
  18706. var RenderingGroup = /** @class */ (function () {
  18707. /**
  18708. * Creates a new rendering group.
  18709. * @param index The rendering group index
  18710. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18711. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18712. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18713. */
  18714. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18715. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18716. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18717. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18718. this.index = index;
  18719. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18720. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18721. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18722. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18723. this._particleSystems = new BABYLON.SmartArray(256);
  18724. this._spriteManagers = new BABYLON.SmartArray(256);
  18725. this._edgesRenderers = new BABYLON.SmartArray(16);
  18726. this._scene = scene;
  18727. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18728. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18729. this.transparentSortCompareFn = transparentSortCompareFn;
  18730. }
  18731. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18732. /**
  18733. * Set the opaque sort comparison function.
  18734. * If null the sub meshes will be render in the order they were created
  18735. */
  18736. set: function (value) {
  18737. this._opaqueSortCompareFn = value;
  18738. if (value) {
  18739. this._renderOpaque = this.renderOpaqueSorted;
  18740. }
  18741. else {
  18742. this._renderOpaque = RenderingGroup.renderUnsorted;
  18743. }
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18749. /**
  18750. * Set the alpha test sort comparison function.
  18751. * If null the sub meshes will be render in the order they were created
  18752. */
  18753. set: function (value) {
  18754. this._alphaTestSortCompareFn = value;
  18755. if (value) {
  18756. this._renderAlphaTest = this.renderAlphaTestSorted;
  18757. }
  18758. else {
  18759. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18760. }
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18766. /**
  18767. * Set the transparent sort comparison function.
  18768. * If null the sub meshes will be render in the order they were created
  18769. */
  18770. set: function (value) {
  18771. if (value) {
  18772. this._transparentSortCompareFn = value;
  18773. }
  18774. else {
  18775. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18776. }
  18777. this._renderTransparent = this.renderTransparentSorted;
  18778. },
  18779. enumerable: true,
  18780. configurable: true
  18781. });
  18782. /**
  18783. * Render all the sub meshes contained in the group.
  18784. * @param customRenderFunction Used to override the default render behaviour of the group.
  18785. * @returns true if rendered some submeshes.
  18786. */
  18787. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18788. if (customRenderFunction) {
  18789. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18790. return;
  18791. }
  18792. var engine = this._scene.getEngine();
  18793. // Depth only
  18794. if (this._depthOnlySubMeshes.length !== 0) {
  18795. engine.setAlphaTesting(true);
  18796. engine.setColorWrite(false);
  18797. this._renderAlphaTest(this._depthOnlySubMeshes);
  18798. engine.setAlphaTesting(false);
  18799. engine.setColorWrite(true);
  18800. }
  18801. // Opaque
  18802. if (this._opaqueSubMeshes.length !== 0) {
  18803. this._renderOpaque(this._opaqueSubMeshes);
  18804. }
  18805. // Alpha test
  18806. if (this._alphaTestSubMeshes.length !== 0) {
  18807. engine.setAlphaTesting(true);
  18808. this._renderAlphaTest(this._alphaTestSubMeshes);
  18809. engine.setAlphaTesting(false);
  18810. }
  18811. var stencilState = engine.getStencilBuffer();
  18812. engine.setStencilBuffer(false);
  18813. // Sprites
  18814. if (renderSprites) {
  18815. this._renderSprites();
  18816. }
  18817. // Particles
  18818. if (renderParticles) {
  18819. this._renderParticles(activeMeshes);
  18820. }
  18821. if (this.onBeforeTransparentRendering) {
  18822. this.onBeforeTransparentRendering();
  18823. }
  18824. // Transparent
  18825. if (this._transparentSubMeshes.length !== 0) {
  18826. this._renderTransparent(this._transparentSubMeshes);
  18827. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18828. }
  18829. // Set back stencil to false in case it changes before the edge renderer.
  18830. engine.setStencilBuffer(false);
  18831. // Edges
  18832. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18833. this._edgesRenderers.data[edgesRendererIndex].render();
  18834. }
  18835. // Restore Stencil state.
  18836. engine.setStencilBuffer(stencilState);
  18837. };
  18838. /**
  18839. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18840. * @param subMeshes The submeshes to render
  18841. */
  18842. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18843. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18844. };
  18845. /**
  18846. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18847. * @param subMeshes The submeshes to render
  18848. */
  18849. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18850. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18851. };
  18852. /**
  18853. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18854. * @param subMeshes The submeshes to render
  18855. */
  18856. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18857. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18858. };
  18859. /**
  18860. * Renders the submeshes in a specified order.
  18861. * @param subMeshes The submeshes to sort before render
  18862. * @param sortCompareFn The comparison function use to sort
  18863. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18864. * @param transparent Specifies to activate blending if true
  18865. */
  18866. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18867. var subIndex = 0;
  18868. var subMesh;
  18869. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18870. for (; subIndex < subMeshes.length; subIndex++) {
  18871. subMesh = subMeshes.data[subIndex];
  18872. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18873. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18874. }
  18875. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18876. if (sortCompareFn) {
  18877. sortedArray.sort(sortCompareFn);
  18878. }
  18879. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18880. subMesh = sortedArray[subIndex];
  18881. if (transparent) {
  18882. var material = subMesh.getMaterial();
  18883. if (material && material.needDepthPrePass) {
  18884. var engine = material.getScene().getEngine();
  18885. engine.setColorWrite(false);
  18886. engine.setAlphaTesting(true);
  18887. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18888. subMesh.render(false);
  18889. engine.setAlphaTesting(false);
  18890. engine.setColorWrite(true);
  18891. }
  18892. }
  18893. subMesh.render(transparent);
  18894. }
  18895. };
  18896. /**
  18897. * Renders the submeshes in the order they were dispatched (no sort applied).
  18898. * @param subMeshes The submeshes to render
  18899. */
  18900. RenderingGroup.renderUnsorted = function (subMeshes) {
  18901. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18902. var submesh = subMeshes.data[subIndex];
  18903. submesh.render(false);
  18904. }
  18905. };
  18906. /**
  18907. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18908. * are rendered back to front if in the same alpha index.
  18909. *
  18910. * @param a The first submesh
  18911. * @param b The second submesh
  18912. * @returns The result of the comparison
  18913. */
  18914. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18915. // Alpha index first
  18916. if (a._alphaIndex > b._alphaIndex) {
  18917. return 1;
  18918. }
  18919. if (a._alphaIndex < b._alphaIndex) {
  18920. return -1;
  18921. }
  18922. // Then distance to camera
  18923. return RenderingGroup.backToFrontSortCompare(a, b);
  18924. };
  18925. /**
  18926. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18927. * are rendered back to front.
  18928. *
  18929. * @param a The first submesh
  18930. * @param b The second submesh
  18931. * @returns The result of the comparison
  18932. */
  18933. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18934. // Then distance to camera
  18935. if (a._distanceToCamera < b._distanceToCamera) {
  18936. return 1;
  18937. }
  18938. if (a._distanceToCamera > b._distanceToCamera) {
  18939. return -1;
  18940. }
  18941. return 0;
  18942. };
  18943. /**
  18944. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18945. * are rendered front to back (prevent overdraw).
  18946. *
  18947. * @param a The first submesh
  18948. * @param b The second submesh
  18949. * @returns The result of the comparison
  18950. */
  18951. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18952. // Then distance to camera
  18953. if (a._distanceToCamera < b._distanceToCamera) {
  18954. return -1;
  18955. }
  18956. if (a._distanceToCamera > b._distanceToCamera) {
  18957. return 1;
  18958. }
  18959. return 0;
  18960. };
  18961. /**
  18962. * Resets the different lists of submeshes to prepare a new frame.
  18963. */
  18964. RenderingGroup.prototype.prepare = function () {
  18965. this._opaqueSubMeshes.reset();
  18966. this._transparentSubMeshes.reset();
  18967. this._alphaTestSubMeshes.reset();
  18968. this._depthOnlySubMeshes.reset();
  18969. this._particleSystems.reset();
  18970. this._spriteManagers.reset();
  18971. this._edgesRenderers.reset();
  18972. };
  18973. RenderingGroup.prototype.dispose = function () {
  18974. this._opaqueSubMeshes.dispose();
  18975. this._transparentSubMeshes.dispose();
  18976. this._alphaTestSubMeshes.dispose();
  18977. this._depthOnlySubMeshes.dispose();
  18978. this._particleSystems.dispose();
  18979. this._spriteManagers.dispose();
  18980. this._edgesRenderers.dispose();
  18981. };
  18982. /**
  18983. * Inserts the submesh in its correct queue depending on its material.
  18984. * @param subMesh The submesh to dispatch
  18985. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18986. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18987. */
  18988. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18989. // Get mesh and materials if not provided
  18990. if (mesh === undefined) {
  18991. mesh = subMesh.getMesh();
  18992. }
  18993. if (material === undefined) {
  18994. material = subMesh.getMaterial();
  18995. }
  18996. if (material === null || material === undefined) {
  18997. return;
  18998. }
  18999. if (material.needAlphaBlendingForMesh(mesh)) {
  19000. this._transparentSubMeshes.push(subMesh);
  19001. }
  19002. else if (material.needAlphaTesting()) {
  19003. if (material.needDepthPrePass) {
  19004. this._depthOnlySubMeshes.push(subMesh);
  19005. }
  19006. this._alphaTestSubMeshes.push(subMesh);
  19007. }
  19008. else {
  19009. if (material.needDepthPrePass) {
  19010. this._depthOnlySubMeshes.push(subMesh);
  19011. }
  19012. this._opaqueSubMeshes.push(subMesh); // Opaque
  19013. }
  19014. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19015. this._edgesRenderers.push(mesh._edgesRenderer);
  19016. }
  19017. };
  19018. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19019. this._spriteManagers.push(spriteManager);
  19020. };
  19021. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19022. this._particleSystems.push(particleSystem);
  19023. };
  19024. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19025. if (this._particleSystems.length === 0) {
  19026. return;
  19027. }
  19028. // Particles
  19029. var activeCamera = this._scene.activeCamera;
  19030. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19031. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19032. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19033. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19034. continue;
  19035. }
  19036. var emitter = particleSystem.emitter;
  19037. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19038. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19039. }
  19040. }
  19041. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19042. };
  19043. RenderingGroup.prototype._renderSprites = function () {
  19044. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19045. return;
  19046. }
  19047. // Sprites
  19048. var activeCamera = this._scene.activeCamera;
  19049. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19050. for (var id = 0; id < this._spriteManagers.length; id++) {
  19051. var spriteManager = this._spriteManagers.data[id];
  19052. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19053. spriteManager.render();
  19054. }
  19055. }
  19056. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19057. };
  19058. return RenderingGroup;
  19059. }());
  19060. BABYLON.RenderingGroup = RenderingGroup;
  19061. })(BABYLON || (BABYLON = {}));
  19062. //# sourceMappingURL=babylon.renderingGroup.js.map
  19063. var BABYLON;
  19064. (function (BABYLON) {
  19065. var ClickInfo = /** @class */ (function () {
  19066. function ClickInfo() {
  19067. this._singleClick = false;
  19068. this._doubleClick = false;
  19069. this._hasSwiped = false;
  19070. this._ignore = false;
  19071. }
  19072. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19073. get: function () {
  19074. return this._singleClick;
  19075. },
  19076. set: function (b) {
  19077. this._singleClick = b;
  19078. },
  19079. enumerable: true,
  19080. configurable: true
  19081. });
  19082. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19083. get: function () {
  19084. return this._doubleClick;
  19085. },
  19086. set: function (b) {
  19087. this._doubleClick = b;
  19088. },
  19089. enumerable: true,
  19090. configurable: true
  19091. });
  19092. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19093. get: function () {
  19094. return this._hasSwiped;
  19095. },
  19096. set: function (b) {
  19097. this._hasSwiped = b;
  19098. },
  19099. enumerable: true,
  19100. configurable: true
  19101. });
  19102. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19103. get: function () {
  19104. return this._ignore;
  19105. },
  19106. set: function (b) {
  19107. this._ignore = b;
  19108. },
  19109. enumerable: true,
  19110. configurable: true
  19111. });
  19112. return ClickInfo;
  19113. }());
  19114. /**
  19115. * This class is used by the onRenderingGroupObservable
  19116. */
  19117. var RenderingGroupInfo = /** @class */ (function () {
  19118. function RenderingGroupInfo() {
  19119. }
  19120. /**
  19121. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19122. * This stage will be fired no matter what
  19123. */
  19124. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19125. /**
  19126. * Called before opaque object are rendered.
  19127. * This stage will be fired only if there's 3D Opaque content to render
  19128. */
  19129. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19130. /**
  19131. * Called after the opaque objects are rendered and before the transparent ones
  19132. * This stage will be fired only if there's 3D transparent content to render
  19133. */
  19134. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19135. /**
  19136. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19137. * This stage will be fired no matter what
  19138. */
  19139. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19140. return RenderingGroupInfo;
  19141. }());
  19142. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19143. /**
  19144. * Represents a scene to be rendered by the engine.
  19145. * @see http://doc.babylonjs.com/page.php?p=21911
  19146. */
  19147. var Scene = /** @class */ (function () {
  19148. /**
  19149. * @constructor
  19150. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19151. */
  19152. function Scene(engine) {
  19153. // Members
  19154. this.autoClear = true;
  19155. this.autoClearDepthAndStencil = true;
  19156. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19157. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19158. this.forceWireframe = false;
  19159. this._forcePointsCloud = false;
  19160. this.forceShowBoundingBoxes = false;
  19161. this.animationsEnabled = true;
  19162. this.useConstantAnimationDeltaTime = false;
  19163. this.constantlyUpdateMeshUnderPointer = false;
  19164. this.hoverCursor = "pointer";
  19165. this.defaultCursor = "";
  19166. /**
  19167. * This is used to call preventDefault() on pointer down
  19168. * in order to block unwanted artifacts like system double clicks
  19169. */
  19170. this.preventDefaultOnPointerDown = true;
  19171. // Metadata
  19172. this.metadata = null;
  19173. /**
  19174. * An event triggered when the scene is disposed.
  19175. * @type {BABYLON.Observable}
  19176. */
  19177. this.onDisposeObservable = new BABYLON.Observable();
  19178. /**
  19179. * An event triggered before rendering the scene (right after animations and physics)
  19180. * @type {BABYLON.Observable}
  19181. */
  19182. this.onBeforeRenderObservable = new BABYLON.Observable();
  19183. /**
  19184. * An event triggered after rendering the scene
  19185. * @type {BABYLON.Observable}
  19186. */
  19187. this.onAfterRenderObservable = new BABYLON.Observable();
  19188. /**
  19189. * An event triggered before animating the scene
  19190. * @type {BABYLON.Observable}
  19191. */
  19192. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19193. /**
  19194. * An event triggered after animations processing
  19195. * @type {BABYLON.Observable}
  19196. */
  19197. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19198. /**
  19199. * An event triggered before draw calls are ready to be sent
  19200. * @type {BABYLON.Observable}
  19201. */
  19202. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19203. /**
  19204. * An event triggered after draw calls have been sent
  19205. * @type {BABYLON.Observable}
  19206. */
  19207. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19208. /**
  19209. * An event triggered when physic simulation is about to be run
  19210. * @type {BABYLON.Observable}
  19211. */
  19212. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19213. /**
  19214. * An event triggered when physic simulation has been done
  19215. * @type {BABYLON.Observable}
  19216. */
  19217. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19218. /**
  19219. * An event triggered when the scene is ready
  19220. * @type {BABYLON.Observable}
  19221. */
  19222. this.onReadyObservable = new BABYLON.Observable();
  19223. /**
  19224. * An event triggered before rendering a camera
  19225. * @type {BABYLON.Observable}
  19226. */
  19227. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19228. /**
  19229. * An event triggered after rendering a camera
  19230. * @type {BABYLON.Observable}
  19231. */
  19232. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19233. /**
  19234. * An event triggered when active meshes evaluation is about to start
  19235. * @type {BABYLON.Observable}
  19236. */
  19237. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19238. /**
  19239. * An event triggered when active meshes evaluation is done
  19240. * @type {BABYLON.Observable}
  19241. */
  19242. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when particles rendering is about to start
  19245. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19246. * @type {BABYLON.Observable}
  19247. */
  19248. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19249. /**
  19250. * An event triggered when particles rendering is done
  19251. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19252. * @type {BABYLON.Observable}
  19253. */
  19254. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19255. /**
  19256. * An event triggered when sprites rendering is about to start
  19257. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19258. * @type {BABYLON.Observable}
  19259. */
  19260. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19261. /**
  19262. * An event triggered when sprites rendering is done
  19263. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19264. * @type {BABYLON.Observable}
  19265. */
  19266. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19267. /**
  19268. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19269. * @type {BABYLON.Observable}
  19270. */
  19271. this.onDataLoadedObservable = new BABYLON.Observable();
  19272. /**
  19273. * An event triggered when a camera is created
  19274. * @type {BABYLON.Observable}
  19275. */
  19276. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19277. /**
  19278. * An event triggered when a camera is removed
  19279. * @type {BABYLON.Observable}
  19280. */
  19281. this.onCameraRemovedObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when a light is created
  19284. * @type {BABYLON.Observable}
  19285. */
  19286. this.onNewLightAddedObservable = new BABYLON.Observable();
  19287. /**
  19288. * An event triggered when a light is removed
  19289. * @type {BABYLON.Observable}
  19290. */
  19291. this.onLightRemovedObservable = new BABYLON.Observable();
  19292. /**
  19293. * An event triggered when a geometry is created
  19294. * @type {BABYLON.Observable}
  19295. */
  19296. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19297. /**
  19298. * An event triggered when a geometry is removed
  19299. * @type {BABYLON.Observable}
  19300. */
  19301. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19302. /**
  19303. * An event triggered when a transform node is created
  19304. * @type {BABYLON.Observable}
  19305. */
  19306. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19307. /**
  19308. * An event triggered when a transform node is removed
  19309. * @type {BABYLON.Observable}
  19310. */
  19311. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19312. /**
  19313. * An event triggered when a mesh is created
  19314. * @type {BABYLON.Observable}
  19315. */
  19316. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19317. /**
  19318. * An event triggered when a mesh is removed
  19319. * @type {BABYLON.Observable}
  19320. */
  19321. this.onMeshRemovedObservable = new BABYLON.Observable();
  19322. /**
  19323. * An event triggered when render targets are about to be rendered
  19324. * Can happen multiple times per frame.
  19325. * @type {BABYLON.Observable}
  19326. */
  19327. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19328. /**
  19329. * An event triggered when render targets were rendered.
  19330. * Can happen multiple times per frame.
  19331. * @type {BABYLON.Observable}
  19332. */
  19333. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19334. /**
  19335. * An event triggered before calculating deterministic simulation step
  19336. * @type {BABYLON.Observable}
  19337. */
  19338. this.onBeforeStepObservable = new BABYLON.Observable();
  19339. /**
  19340. * An event triggered after calculating deterministic simulation step
  19341. * @type {BABYLON.Observable}
  19342. */
  19343. this.onAfterStepObservable = new BABYLON.Observable();
  19344. /**
  19345. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19346. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19347. * 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)
  19348. */
  19349. this.onRenderingGroupObservable = new BABYLON.Observable();
  19350. // Animations
  19351. this.animations = [];
  19352. /**
  19353. * 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).
  19354. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19355. */
  19356. this.onPrePointerObservable = new BABYLON.Observable();
  19357. /**
  19358. * Observable event triggered each time an input event is received from the rendering canvas
  19359. */
  19360. this.onPointerObservable = new BABYLON.Observable();
  19361. this._meshPickProceed = false;
  19362. this._currentPickResult = null;
  19363. this._previousPickResult = null;
  19364. this._totalPointersPressed = 0;
  19365. this._doubleClickOccured = false;
  19366. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19367. this.cameraToUseForPointers = null;
  19368. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19369. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19370. this._startingPointerTime = 0;
  19371. this._previousStartingPointerTime = 0;
  19372. // Deterministic lockstep
  19373. this._timeAccumulator = 0;
  19374. this._currentStepId = 0;
  19375. this._currentInternalStep = 0;
  19376. // Keyboard
  19377. /**
  19378. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19379. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19380. */
  19381. this.onPreKeyboardObservable = new BABYLON.Observable();
  19382. /**
  19383. * Observable event triggered each time an keyboard event is received from the hosting window
  19384. */
  19385. this.onKeyboardObservable = new BABYLON.Observable();
  19386. // Coordinate system
  19387. /**
  19388. * use right-handed coordinate system on this scene.
  19389. * @type {boolean}
  19390. */
  19391. this._useRightHandedSystem = false;
  19392. // Fog
  19393. this._fogEnabled = true;
  19394. this._fogMode = Scene.FOGMODE_NONE;
  19395. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19396. this.fogDensity = 0.1;
  19397. this.fogStart = 0;
  19398. this.fogEnd = 1000.0;
  19399. // Lights
  19400. /**
  19401. * is shadow enabled on this scene.
  19402. * @type {boolean}
  19403. */
  19404. this._shadowsEnabled = true;
  19405. /**
  19406. * is light enabled on this scene.
  19407. * @type {boolean}
  19408. */
  19409. this._lightsEnabled = true;
  19410. /**
  19411. * All of the lights added to this scene.
  19412. * @see BABYLON.Light
  19413. * @type {BABYLON.Light[]}
  19414. */
  19415. this.lights = new Array();
  19416. // Cameras
  19417. /** All of the cameras added to this scene. */
  19418. this.cameras = new Array();
  19419. /** All of the active cameras added to this scene. */
  19420. this.activeCameras = new Array();
  19421. // Meshes
  19422. /**
  19423. * All of the tranform nodes added to this scene.
  19424. * @see BABYLON.TransformNode
  19425. * @type {BABYLON.TransformNode[]}
  19426. */
  19427. this.transformNodes = new Array();
  19428. /**
  19429. * All of the (abstract) meshes added to this scene.
  19430. * @see BABYLON.AbstractMesh
  19431. * @type {BABYLON.AbstractMesh[]}
  19432. */
  19433. this.meshes = new Array();
  19434. /**
  19435. * All of the animation groups added to this scene.
  19436. * @see BABYLON.AnimationGroup
  19437. * @type {BABYLON.AnimationGroup[]}
  19438. */
  19439. this.animationGroups = new Array();
  19440. // Geometries
  19441. this._geometries = new Array();
  19442. this.materials = new Array();
  19443. this.multiMaterials = new Array();
  19444. // Textures
  19445. this._texturesEnabled = true;
  19446. this.textures = new Array();
  19447. // Particles
  19448. this.particlesEnabled = true;
  19449. this.particleSystems = new Array();
  19450. // Sprites
  19451. this.spritesEnabled = true;
  19452. this.spriteManagers = new Array();
  19453. // Layers
  19454. this.layers = new Array();
  19455. this.highlightLayers = new Array();
  19456. // Skeletons
  19457. this._skeletonsEnabled = true;
  19458. this.skeletons = new Array();
  19459. // Morph targets
  19460. this.morphTargetManagers = new Array();
  19461. // Lens flares
  19462. this.lensFlaresEnabled = true;
  19463. this.lensFlareSystems = new Array();
  19464. // Collisions
  19465. this.collisionsEnabled = true;
  19466. /** Defines the gravity applied to this scene */
  19467. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19468. // Postprocesses
  19469. this.postProcesses = new Array();
  19470. this.postProcessesEnabled = true;
  19471. // Customs render targets
  19472. this.renderTargetsEnabled = true;
  19473. this.dumpNextRenderTargets = false;
  19474. this.customRenderTargets = new Array();
  19475. // Imported meshes
  19476. this.importedMeshesFiles = new Array();
  19477. // Probes
  19478. this.probesEnabled = true;
  19479. this.reflectionProbes = new Array();
  19480. this._actionManagers = new Array();
  19481. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19482. // Procedural textures
  19483. this.proceduralTexturesEnabled = true;
  19484. this._proceduralTextures = new Array();
  19485. this.soundTracks = new Array();
  19486. this._audioEnabled = true;
  19487. this._headphone = false;
  19488. // Performance counters
  19489. this._totalVertices = new BABYLON.PerfCounter();
  19490. this._activeIndices = new BABYLON.PerfCounter();
  19491. this._activeParticles = new BABYLON.PerfCounter();
  19492. this._activeBones = new BABYLON.PerfCounter();
  19493. this._animationTime = 0;
  19494. this.animationTimeScale = 1;
  19495. this._renderId = 0;
  19496. this._executeWhenReadyTimeoutId = -1;
  19497. this._intermediateRendering = false;
  19498. this._viewUpdateFlag = -1;
  19499. this._projectionUpdateFlag = -1;
  19500. this._alternateViewUpdateFlag = -1;
  19501. this._alternateProjectionUpdateFlag = -1;
  19502. this._toBeDisposed = new BABYLON.SmartArray(256);
  19503. this._activeRequests = new Array();
  19504. this._pendingData = new Array();
  19505. this._isDisposed = false;
  19506. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19507. this._activeMeshes = new BABYLON.SmartArray(256);
  19508. this._processedMaterials = new BABYLON.SmartArray(256);
  19509. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19510. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19511. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19512. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19513. this._activeAnimatables = new Array();
  19514. this._transformMatrix = BABYLON.Matrix.Zero();
  19515. this._useAlternateCameraConfiguration = false;
  19516. this._alternateRendering = false;
  19517. this.requireLightSorting = false;
  19518. this._activeMeshesFrozen = false;
  19519. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19520. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19521. this._engine.scenes.push(this);
  19522. this._uid = null;
  19523. this._renderingManager = new BABYLON.RenderingManager(this);
  19524. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19525. if (BABYLON.OutlineRenderer) {
  19526. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19527. }
  19528. if (BABYLON.Tools.IsWindowObjectExist()) {
  19529. this.attachControl();
  19530. }
  19531. //simplification queue
  19532. if (BABYLON.SimplificationQueue) {
  19533. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19534. }
  19535. //collision coordinator initialization. For now legacy per default.
  19536. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19537. // Uniform Buffer
  19538. this._createUbo();
  19539. // Default Image processing definition.
  19540. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19541. }
  19542. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19543. /** The fog is deactivated */
  19544. get: function () {
  19545. return Scene._FOGMODE_NONE;
  19546. },
  19547. enumerable: true,
  19548. configurable: true
  19549. });
  19550. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19551. /** The fog density is following an exponential function */
  19552. get: function () {
  19553. return Scene._FOGMODE_EXP;
  19554. },
  19555. enumerable: true,
  19556. configurable: true
  19557. });
  19558. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19559. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19560. get: function () {
  19561. return Scene._FOGMODE_EXP2;
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19567. /** The fog density is following a linear function. */
  19568. get: function () {
  19569. return Scene._FOGMODE_LINEAR;
  19570. },
  19571. enumerable: true,
  19572. configurable: true
  19573. });
  19574. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19575. /**
  19576. * Texture used in all pbr material as the reflection texture.
  19577. * As in the majority of the scene they are the same (exception for multi room and so on),
  19578. * this is easier to reference from here than from all the materials.
  19579. */
  19580. get: function () {
  19581. return this._environmentTexture;
  19582. },
  19583. /**
  19584. * Texture used in all pbr material as the reflection texture.
  19585. * As in the majority of the scene they are the same (exception for multi room and so on),
  19586. * this is easier to set here than in all the materials.
  19587. */
  19588. set: function (value) {
  19589. if (this._environmentTexture === value) {
  19590. return;
  19591. }
  19592. this._environmentTexture = value;
  19593. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19599. /**
  19600. * Default image processing configuration used either in the rendering
  19601. * Forward main pass or through the imageProcessingPostProcess if present.
  19602. * As in the majority of the scene they are the same (exception for multi camera),
  19603. * this is easier to reference from here than from all the materials and post process.
  19604. *
  19605. * No setter as we it is a shared configuration, you can set the values instead.
  19606. */
  19607. get: function () {
  19608. return this._imageProcessingConfiguration;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19614. get: function () {
  19615. return this._forcePointsCloud;
  19616. },
  19617. set: function (value) {
  19618. if (this._forcePointsCloud === value) {
  19619. return;
  19620. }
  19621. this._forcePointsCloud = value;
  19622. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19623. },
  19624. enumerable: true,
  19625. configurable: true
  19626. });
  19627. Object.defineProperty(Scene.prototype, "onDispose", {
  19628. /** A function to be executed when this scene is disposed. */
  19629. set: function (callback) {
  19630. if (this._onDisposeObserver) {
  19631. this.onDisposeObservable.remove(this._onDisposeObserver);
  19632. }
  19633. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19634. },
  19635. enumerable: true,
  19636. configurable: true
  19637. });
  19638. Object.defineProperty(Scene.prototype, "beforeRender", {
  19639. /** A function to be executed before rendering this scene */
  19640. set: function (callback) {
  19641. if (this._onBeforeRenderObserver) {
  19642. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19643. }
  19644. if (callback) {
  19645. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19646. }
  19647. },
  19648. enumerable: true,
  19649. configurable: true
  19650. });
  19651. Object.defineProperty(Scene.prototype, "afterRender", {
  19652. /** A function to be executed after rendering this scene */
  19653. set: function (callback) {
  19654. if (this._onAfterRenderObserver) {
  19655. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19656. }
  19657. if (callback) {
  19658. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19659. }
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19665. set: function (callback) {
  19666. if (this._onBeforeCameraRenderObserver) {
  19667. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19668. }
  19669. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19670. },
  19671. enumerable: true,
  19672. configurable: true
  19673. });
  19674. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19675. set: function (callback) {
  19676. if (this._onAfterCameraRenderObserver) {
  19677. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19678. }
  19679. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19685. get: function () {
  19686. if (!this._gamepadManager) {
  19687. this._gamepadManager = new BABYLON.GamepadManager(this);
  19688. }
  19689. return this._gamepadManager;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19695. get: function () {
  19696. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19702. get: function () {
  19703. return this._useRightHandedSystem;
  19704. },
  19705. set: function (value) {
  19706. if (this._useRightHandedSystem === value) {
  19707. return;
  19708. }
  19709. this._useRightHandedSystem = value;
  19710. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Scene.prototype.setStepId = function (newStepId) {
  19716. this._currentStepId = newStepId;
  19717. };
  19718. ;
  19719. Scene.prototype.getStepId = function () {
  19720. return this._currentStepId;
  19721. };
  19722. ;
  19723. Scene.prototype.getInternalStep = function () {
  19724. return this._currentInternalStep;
  19725. };
  19726. ;
  19727. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19728. get: function () {
  19729. return this._fogEnabled;
  19730. },
  19731. /**
  19732. * is fog enabled on this scene.
  19733. */
  19734. set: function (value) {
  19735. if (this._fogEnabled === value) {
  19736. return;
  19737. }
  19738. this._fogEnabled = value;
  19739. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(Scene.prototype, "fogMode", {
  19745. get: function () {
  19746. return this._fogMode;
  19747. },
  19748. set: function (value) {
  19749. if (this._fogMode === value) {
  19750. return;
  19751. }
  19752. this._fogMode = value;
  19753. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19759. get: function () {
  19760. return this._shadowsEnabled;
  19761. },
  19762. set: function (value) {
  19763. if (this._shadowsEnabled === value) {
  19764. return;
  19765. }
  19766. this._shadowsEnabled = value;
  19767. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19773. get: function () {
  19774. return this._lightsEnabled;
  19775. },
  19776. set: function (value) {
  19777. if (this._lightsEnabled === value) {
  19778. return;
  19779. }
  19780. this._lightsEnabled = value;
  19781. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19787. /** The default material used on meshes when no material is affected */
  19788. get: function () {
  19789. if (!this._defaultMaterial) {
  19790. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19791. }
  19792. return this._defaultMaterial;
  19793. },
  19794. /** The default material used on meshes when no material is affected */
  19795. set: function (value) {
  19796. this._defaultMaterial = value;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19802. get: function () {
  19803. return this._texturesEnabled;
  19804. },
  19805. set: function (value) {
  19806. if (this._texturesEnabled === value) {
  19807. return;
  19808. }
  19809. this._texturesEnabled = value;
  19810. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19816. get: function () {
  19817. return this._skeletonsEnabled;
  19818. },
  19819. set: function (value) {
  19820. if (this._skeletonsEnabled === value) {
  19821. return;
  19822. }
  19823. this._skeletonsEnabled = value;
  19824. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19830. get: function () {
  19831. if (!this._postProcessRenderPipelineManager) {
  19832. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19833. }
  19834. return this._postProcessRenderPipelineManager;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19840. get: function () {
  19841. if (!this._mainSoundTrack) {
  19842. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19843. }
  19844. return this._mainSoundTrack;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19850. get: function () {
  19851. return this._alternateRendering;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19857. get: function () {
  19858. return this._frustumPlanes;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(Scene.prototype, "debugLayer", {
  19864. // Properties
  19865. get: function () {
  19866. if (!this._debugLayer) {
  19867. this._debugLayer = new BABYLON.DebugLayer(this);
  19868. }
  19869. return this._debugLayer;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19875. get: function () {
  19876. return this._workerCollisions;
  19877. },
  19878. set: function (enabled) {
  19879. if (!BABYLON.CollisionCoordinatorLegacy) {
  19880. return;
  19881. }
  19882. enabled = (enabled && !!Worker);
  19883. this._workerCollisions = enabled;
  19884. if (this.collisionCoordinator) {
  19885. this.collisionCoordinator.destroy();
  19886. }
  19887. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19888. this.collisionCoordinator.init(this);
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19894. get: function () {
  19895. return this._selectionOctree;
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19901. /**
  19902. * The mesh that is currently under the pointer.
  19903. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19904. */
  19905. get: function () {
  19906. return this._pointerOverMesh;
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. Object.defineProperty(Scene.prototype, "pointerX", {
  19912. /**
  19913. * Current on-screen X position of the pointer
  19914. * @return {number} X position of the pointer
  19915. */
  19916. get: function () {
  19917. return this._pointerX;
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(Scene.prototype, "pointerY", {
  19923. /**
  19924. * Current on-screen Y position of the pointer
  19925. * @return {number} Y position of the pointer
  19926. */
  19927. get: function () {
  19928. return this._pointerY;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Scene.prototype.getCachedMaterial = function () {
  19934. return this._cachedMaterial;
  19935. };
  19936. Scene.prototype.getCachedEffect = function () {
  19937. return this._cachedEffect;
  19938. };
  19939. Scene.prototype.getCachedVisibility = function () {
  19940. return this._cachedVisibility;
  19941. };
  19942. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19943. if (visibility === void 0) { visibility = 1; }
  19944. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19945. };
  19946. Scene.prototype.getBoundingBoxRenderer = function () {
  19947. if (!this._boundingBoxRenderer) {
  19948. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19949. }
  19950. return this._boundingBoxRenderer;
  19951. };
  19952. Scene.prototype.getOutlineRenderer = function () {
  19953. return this._outlineRenderer;
  19954. };
  19955. Scene.prototype.getEngine = function () {
  19956. return this._engine;
  19957. };
  19958. Scene.prototype.getTotalVertices = function () {
  19959. return this._totalVertices.current;
  19960. };
  19961. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19962. get: function () {
  19963. return this._totalVertices;
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Scene.prototype.getActiveIndices = function () {
  19969. return this._activeIndices.current;
  19970. };
  19971. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19972. get: function () {
  19973. return this._activeIndices;
  19974. },
  19975. enumerable: true,
  19976. configurable: true
  19977. });
  19978. Scene.prototype.getActiveParticles = function () {
  19979. return this._activeParticles.current;
  19980. };
  19981. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19982. get: function () {
  19983. return this._activeParticles;
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Scene.prototype.getActiveBones = function () {
  19989. return this._activeBones.current;
  19990. };
  19991. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19992. get: function () {
  19993. return this._activeBones;
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. // Stats
  19999. Scene.prototype.getInterFramePerfCounter = function () {
  20000. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20001. return 0;
  20002. };
  20003. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20004. get: function () {
  20005. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20006. return null;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Scene.prototype.getLastFrameDuration = function () {
  20012. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20013. return 0;
  20014. };
  20015. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20016. get: function () {
  20017. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20018. return null;
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20024. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20025. return 0;
  20026. };
  20027. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20028. get: function () {
  20029. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20030. return null;
  20031. },
  20032. enumerable: true,
  20033. configurable: true
  20034. });
  20035. Scene.prototype.getActiveMeshes = function () {
  20036. return this._activeMeshes;
  20037. };
  20038. Scene.prototype.getRenderTargetsDuration = function () {
  20039. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20040. return 0;
  20041. };
  20042. Scene.prototype.getRenderDuration = function () {
  20043. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20044. return 0;
  20045. };
  20046. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20047. get: function () {
  20048. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20049. return null;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. Scene.prototype.getParticlesDuration = function () {
  20055. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20056. return 0;
  20057. };
  20058. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20059. get: function () {
  20060. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20061. return null;
  20062. },
  20063. enumerable: true,
  20064. configurable: true
  20065. });
  20066. Scene.prototype.getSpritesDuration = function () {
  20067. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20068. return 0;
  20069. };
  20070. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20071. get: function () {
  20072. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20073. return null;
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Scene.prototype.getAnimationRatio = function () {
  20079. return this._animationRatio;
  20080. };
  20081. Scene.prototype.getRenderId = function () {
  20082. return this._renderId;
  20083. };
  20084. Scene.prototype.incrementRenderId = function () {
  20085. this._renderId++;
  20086. };
  20087. Scene.prototype._updatePointerPosition = function (evt) {
  20088. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20089. if (!canvasRect) {
  20090. return;
  20091. }
  20092. this._pointerX = evt.clientX - canvasRect.left;
  20093. this._pointerY = evt.clientY - canvasRect.top;
  20094. this._unTranslatedPointerX = this._pointerX;
  20095. this._unTranslatedPointerY = this._pointerY;
  20096. };
  20097. Scene.prototype._createUbo = function () {
  20098. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20099. this._sceneUbo.addUniform("viewProjection", 16);
  20100. this._sceneUbo.addUniform("view", 16);
  20101. };
  20102. Scene.prototype._createAlternateUbo = function () {
  20103. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20104. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20105. this._alternateSceneUbo.addUniform("view", 16);
  20106. };
  20107. // Pointers handling
  20108. /**
  20109. * Use this method to simulate a pointer move on a mesh
  20110. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20111. */
  20112. Scene.prototype.simulatePointerMove = function (pickResult) {
  20113. var evt = new PointerEvent("pointermove");
  20114. return this._processPointerMove(pickResult, evt);
  20115. };
  20116. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20117. var canvas = this._engine.getRenderingCanvas();
  20118. if (!canvas) {
  20119. return this;
  20120. }
  20121. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20122. this.setPointerOverSprite(null);
  20123. this.setPointerOverMesh(pickResult.pickedMesh);
  20124. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20125. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20126. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20127. }
  20128. else {
  20129. canvas.style.cursor = this.hoverCursor;
  20130. }
  20131. }
  20132. else {
  20133. canvas.style.cursor = this.defaultCursor;
  20134. }
  20135. }
  20136. else {
  20137. this.setPointerOverMesh(null);
  20138. // Sprites
  20139. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20140. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20141. this.setPointerOverSprite(pickResult.pickedSprite);
  20142. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20143. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20144. }
  20145. else {
  20146. canvas.style.cursor = this.hoverCursor;
  20147. }
  20148. }
  20149. else {
  20150. this.setPointerOverSprite(null);
  20151. // Restore pointer
  20152. canvas.style.cursor = this.defaultCursor;
  20153. }
  20154. }
  20155. if (pickResult) {
  20156. if (this.onPointerMove) {
  20157. this.onPointerMove(evt, pickResult);
  20158. }
  20159. if (this.onPointerObservable.hasObservers()) {
  20160. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20161. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20162. this.onPointerObservable.notifyObservers(pi, type);
  20163. }
  20164. }
  20165. return this;
  20166. };
  20167. /**
  20168. * Use this method to simulate a pointer down on a mesh
  20169. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20170. */
  20171. Scene.prototype.simulatePointerDown = function (pickResult) {
  20172. var evt = new PointerEvent("pointerdown");
  20173. return this._processPointerDown(pickResult, evt);
  20174. };
  20175. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20176. var _this = this;
  20177. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20178. this._pickedDownMesh = pickResult.pickedMesh;
  20179. var actionManager = pickResult.pickedMesh.actionManager;
  20180. if (actionManager) {
  20181. if (actionManager.hasPickTriggers) {
  20182. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20183. switch (evt.button) {
  20184. case 0:
  20185. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20186. break;
  20187. case 1:
  20188. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20189. break;
  20190. case 2:
  20191. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20192. break;
  20193. }
  20194. }
  20195. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20196. window.setTimeout(function () {
  20197. 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);
  20198. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20199. if (_this._totalPointersPressed !== 0 &&
  20200. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20201. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20202. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20203. _this._startingPointerTime = 0;
  20204. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20205. }
  20206. }
  20207. }, Scene.LongPressDelay);
  20208. }
  20209. }
  20210. }
  20211. if (pickResult) {
  20212. if (this.onPointerDown) {
  20213. this.onPointerDown(evt, pickResult);
  20214. }
  20215. if (this.onPointerObservable.hasObservers()) {
  20216. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20217. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20218. this.onPointerObservable.notifyObservers(pi, type);
  20219. }
  20220. }
  20221. return this;
  20222. };
  20223. /**
  20224. * Use this method to simulate a pointer up on a mesh
  20225. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20226. */
  20227. Scene.prototype.simulatePointerUp = function (pickResult) {
  20228. var evt = new PointerEvent("pointerup");
  20229. var clickInfo = new ClickInfo();
  20230. clickInfo.singleClick = true;
  20231. clickInfo.ignore = true;
  20232. return this._processPointerUp(pickResult, evt, clickInfo);
  20233. };
  20234. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20235. if (pickResult && pickResult && pickResult.pickedMesh) {
  20236. this._pickedUpMesh = pickResult.pickedMesh;
  20237. if (this._pickedDownMesh === this._pickedUpMesh) {
  20238. if (this.onPointerPick) {
  20239. this.onPointerPick(evt, pickResult);
  20240. }
  20241. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20242. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20243. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20244. this.onPointerObservable.notifyObservers(pi, type);
  20245. }
  20246. }
  20247. if (pickResult.pickedMesh.actionManager) {
  20248. if (clickInfo.ignore) {
  20249. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20250. }
  20251. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20252. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20253. }
  20254. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20255. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20256. }
  20257. }
  20258. }
  20259. if (this._pickedDownMesh &&
  20260. this._pickedDownMesh.actionManager &&
  20261. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20262. this._pickedDownMesh !== this._pickedUpMesh) {
  20263. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20264. }
  20265. if (this.onPointerUp) {
  20266. this.onPointerUp(evt, pickResult);
  20267. }
  20268. if (this.onPointerObservable.hasObservers()) {
  20269. if (!clickInfo.ignore) {
  20270. if (!clickInfo.hasSwiped) {
  20271. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20272. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20273. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20274. this.onPointerObservable.notifyObservers(pi, type);
  20275. }
  20276. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20277. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20278. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20279. this.onPointerObservable.notifyObservers(pi, type);
  20280. }
  20281. }
  20282. }
  20283. else {
  20284. var type = BABYLON.PointerEventTypes.POINTERUP;
  20285. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20286. this.onPointerObservable.notifyObservers(pi, type);
  20287. }
  20288. }
  20289. return this;
  20290. };
  20291. /**
  20292. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20293. * @param attachUp defines if you want to attach events to pointerup
  20294. * @param attachDown defines if you want to attach events to pointerdown
  20295. * @param attachMove defines if you want to attach events to pointermove
  20296. */
  20297. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20298. var _this = this;
  20299. if (attachUp === void 0) { attachUp = true; }
  20300. if (attachDown === void 0) { attachDown = true; }
  20301. if (attachMove === void 0) { attachMove = true; }
  20302. this._initActionManager = function (act, clickInfo) {
  20303. if (!_this._meshPickProceed) {
  20304. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20305. _this._currentPickResult = pickResult;
  20306. if (pickResult) {
  20307. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20308. }
  20309. _this._meshPickProceed = true;
  20310. }
  20311. return act;
  20312. };
  20313. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20314. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20315. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20316. btn !== _this._previousButtonPressed) {
  20317. _this._doubleClickOccured = false;
  20318. clickInfo.singleClick = true;
  20319. clickInfo.ignore = false;
  20320. cb(clickInfo, _this._currentPickResult);
  20321. }
  20322. };
  20323. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20324. var clickInfo = new ClickInfo();
  20325. _this._currentPickResult = null;
  20326. var act = null;
  20327. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20328. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20329. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20330. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20331. act = _this._initActionManager(act, clickInfo);
  20332. if (act)
  20333. checkPicking = act.hasPickTriggers;
  20334. }
  20335. if (checkPicking) {
  20336. var btn = evt.button;
  20337. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20338. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20339. if (!clickInfo.hasSwiped) {
  20340. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20341. if (!checkSingleClickImmediately) {
  20342. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20343. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20344. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20345. act = _this._initActionManager(act, clickInfo);
  20346. if (act)
  20347. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20348. }
  20349. }
  20350. if (checkSingleClickImmediately) {
  20351. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20352. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20353. btn !== _this._previousButtonPressed) {
  20354. clickInfo.singleClick = true;
  20355. cb(clickInfo, _this._currentPickResult);
  20356. }
  20357. }
  20358. else {
  20359. // wait that no double click has been raised during the double click delay
  20360. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20361. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20362. }
  20363. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20364. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20365. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20366. act = _this._initActionManager(act, clickInfo);
  20367. if (act)
  20368. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20369. }
  20370. if (checkDoubleClick) {
  20371. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20372. if (btn === _this._previousButtonPressed &&
  20373. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20374. !_this._doubleClickOccured) {
  20375. // pointer has not moved for 2 clicks, it's a double click
  20376. if (!clickInfo.hasSwiped &&
  20377. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20378. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20379. _this._previousStartingPointerTime = 0;
  20380. _this._doubleClickOccured = true;
  20381. clickInfo.doubleClick = true;
  20382. clickInfo.ignore = false;
  20383. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20384. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20385. }
  20386. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20387. cb(clickInfo, _this._currentPickResult);
  20388. }
  20389. else {
  20390. _this._doubleClickOccured = false;
  20391. _this._previousStartingPointerTime = _this._startingPointerTime;
  20392. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20393. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20394. _this._previousButtonPressed = btn;
  20395. if (Scene.ExclusiveDoubleClickMode) {
  20396. if (_this._previousDelayedSimpleClickTimeout) {
  20397. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20398. }
  20399. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20400. cb(clickInfo, _this._previousPickResult);
  20401. }
  20402. else {
  20403. cb(clickInfo, _this._currentPickResult);
  20404. }
  20405. }
  20406. }
  20407. else {
  20408. _this._doubleClickOccured = false;
  20409. _this._previousStartingPointerTime = _this._startingPointerTime;
  20410. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20411. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20412. _this._previousButtonPressed = btn;
  20413. }
  20414. }
  20415. }
  20416. }
  20417. clickInfo.ignore = true;
  20418. cb(clickInfo, _this._currentPickResult);
  20419. };
  20420. this._spritePredicate = function (sprite) {
  20421. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20422. };
  20423. this._onPointerMove = function (evt) {
  20424. _this._updatePointerPosition(evt);
  20425. // PreObservable support
  20426. if (_this.onPrePointerObservable.hasObservers()) {
  20427. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20428. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20429. _this.onPrePointerObservable.notifyObservers(pi, type);
  20430. if (pi.skipOnPointerObservable) {
  20431. return;
  20432. }
  20433. }
  20434. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20435. return;
  20436. }
  20437. if (!_this.pointerMovePredicate) {
  20438. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20439. }
  20440. // Meshes
  20441. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20442. _this._processPointerMove(pickResult, evt);
  20443. };
  20444. this._onPointerDown = function (evt) {
  20445. _this._totalPointersPressed++;
  20446. _this._pickedDownMesh = null;
  20447. _this._meshPickProceed = false;
  20448. _this._updatePointerPosition(evt);
  20449. if (_this.preventDefaultOnPointerDown && canvas) {
  20450. evt.preventDefault();
  20451. canvas.focus();
  20452. }
  20453. // PreObservable support
  20454. if (_this.onPrePointerObservable.hasObservers()) {
  20455. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20456. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20457. _this.onPrePointerObservable.notifyObservers(pi, type);
  20458. if (pi.skipOnPointerObservable) {
  20459. return;
  20460. }
  20461. }
  20462. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20463. return;
  20464. }
  20465. _this._startingPointerPosition.x = _this._pointerX;
  20466. _this._startingPointerPosition.y = _this._pointerY;
  20467. _this._startingPointerTime = new Date().getTime();
  20468. if (!_this.pointerDownPredicate) {
  20469. _this.pointerDownPredicate = function (mesh) {
  20470. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20471. };
  20472. }
  20473. // Meshes
  20474. _this._pickedDownMesh = null;
  20475. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20476. _this._processPointerDown(pickResult, evt);
  20477. // Sprites
  20478. _this._pickedDownSprite = null;
  20479. if (_this.spriteManagers.length > 0) {
  20480. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20481. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20482. if (pickResult.pickedSprite.actionManager) {
  20483. _this._pickedDownSprite = pickResult.pickedSprite;
  20484. switch (evt.button) {
  20485. case 0:
  20486. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20487. break;
  20488. case 1:
  20489. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20490. break;
  20491. case 2:
  20492. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20493. break;
  20494. }
  20495. if (pickResult.pickedSprite.actionManager) {
  20496. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20497. }
  20498. }
  20499. }
  20500. }
  20501. };
  20502. this._onPointerUp = function (evt) {
  20503. if (_this._totalPointersPressed === 0) {
  20504. return; // So we need to test it the pointer down was pressed before.
  20505. }
  20506. _this._totalPointersPressed--;
  20507. _this._pickedUpMesh = null;
  20508. _this._meshPickProceed = false;
  20509. _this._updatePointerPosition(evt);
  20510. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20511. // PreObservable support
  20512. if (_this.onPrePointerObservable.hasObservers()) {
  20513. if (!clickInfo.ignore) {
  20514. if (!clickInfo.hasSwiped) {
  20515. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20516. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20517. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20518. _this.onPrePointerObservable.notifyObservers(pi, type);
  20519. if (pi.skipOnPointerObservable) {
  20520. return;
  20521. }
  20522. }
  20523. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20524. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20525. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20526. _this.onPrePointerObservable.notifyObservers(pi, type);
  20527. if (pi.skipOnPointerObservable) {
  20528. return;
  20529. }
  20530. }
  20531. }
  20532. }
  20533. else {
  20534. var type = BABYLON.PointerEventTypes.POINTERUP;
  20535. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20536. _this.onPrePointerObservable.notifyObservers(pi, type);
  20537. if (pi.skipOnPointerObservable) {
  20538. return;
  20539. }
  20540. }
  20541. }
  20542. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20543. return;
  20544. }
  20545. if (!_this.pointerUpPredicate) {
  20546. _this.pointerUpPredicate = function (mesh) {
  20547. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20548. };
  20549. }
  20550. // Meshes
  20551. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20552. _this._initActionManager(null, clickInfo);
  20553. }
  20554. if (!pickResult) {
  20555. pickResult = _this._currentPickResult;
  20556. }
  20557. _this._processPointerUp(pickResult, evt, clickInfo);
  20558. // Sprites
  20559. if (_this.spriteManagers.length > 0) {
  20560. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20561. if (spritePickResult) {
  20562. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20563. if (spritePickResult.pickedSprite.actionManager) {
  20564. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20565. if (spritePickResult.pickedSprite.actionManager) {
  20566. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20567. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20568. }
  20569. }
  20570. }
  20571. }
  20572. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20573. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20574. }
  20575. }
  20576. }
  20577. _this._previousPickResult = _this._currentPickResult;
  20578. });
  20579. };
  20580. this._onKeyDown = function (evt) {
  20581. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20582. if (_this.onPreKeyboardObservable.hasObservers()) {
  20583. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20584. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20585. if (pi.skipOnPointerObservable) {
  20586. return;
  20587. }
  20588. }
  20589. if (_this.onKeyboardObservable.hasObservers()) {
  20590. var pi = new BABYLON.KeyboardInfo(type, evt);
  20591. _this.onKeyboardObservable.notifyObservers(pi, type);
  20592. }
  20593. if (_this.actionManager) {
  20594. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20595. }
  20596. };
  20597. this._onKeyUp = function (evt) {
  20598. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20599. if (_this.onPreKeyboardObservable.hasObservers()) {
  20600. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20601. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20602. if (pi.skipOnPointerObservable) {
  20603. return;
  20604. }
  20605. }
  20606. if (_this.onKeyboardObservable.hasObservers()) {
  20607. var pi = new BABYLON.KeyboardInfo(type, evt);
  20608. _this.onKeyboardObservable.notifyObservers(pi, type);
  20609. }
  20610. if (_this.actionManager) {
  20611. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20612. }
  20613. };
  20614. var engine = this.getEngine();
  20615. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20616. if (!canvas) {
  20617. return;
  20618. }
  20619. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20620. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20621. });
  20622. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20623. if (!canvas) {
  20624. return;
  20625. }
  20626. canvas.removeEventListener("keydown", _this._onKeyDown);
  20627. canvas.removeEventListener("keyup", _this._onKeyUp);
  20628. });
  20629. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20630. var canvas = this._engine.getRenderingCanvas();
  20631. if (!canvas) {
  20632. return;
  20633. }
  20634. if (attachMove) {
  20635. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20636. // Wheel
  20637. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20638. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20639. }
  20640. if (attachDown) {
  20641. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20642. }
  20643. if (attachUp) {
  20644. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20645. }
  20646. canvas.tabIndex = 1;
  20647. };
  20648. Scene.prototype.detachControl = function () {
  20649. var engine = this.getEngine();
  20650. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20651. var canvas = engine.getRenderingCanvas();
  20652. if (!canvas) {
  20653. return;
  20654. }
  20655. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20656. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20657. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20658. if (this._onCanvasBlurObserver) {
  20659. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20660. }
  20661. if (this._onCanvasFocusObserver) {
  20662. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20663. }
  20664. // Wheel
  20665. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20666. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20667. // Keyboard
  20668. canvas.removeEventListener("keydown", this._onKeyDown);
  20669. canvas.removeEventListener("keyup", this._onKeyUp);
  20670. // Observables
  20671. this.onKeyboardObservable.clear();
  20672. this.onPreKeyboardObservable.clear();
  20673. this.onPointerObservable.clear();
  20674. this.onPrePointerObservable.clear();
  20675. };
  20676. /**
  20677. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20678. * Delay loaded resources are not taking in account
  20679. * @return true if all required resources are ready
  20680. */
  20681. Scene.prototype.isReady = function () {
  20682. if (this._isDisposed) {
  20683. return false;
  20684. }
  20685. if (this._pendingData.length > 0) {
  20686. return false;
  20687. }
  20688. var index;
  20689. var engine = this.getEngine();
  20690. // Geometries
  20691. for (index = 0; index < this._geometries.length; index++) {
  20692. var geometry = this._geometries[index];
  20693. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20694. return false;
  20695. }
  20696. }
  20697. // Meshes
  20698. for (index = 0; index < this.meshes.length; index++) {
  20699. var mesh = this.meshes[index];
  20700. if (!mesh.isEnabled()) {
  20701. continue;
  20702. }
  20703. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20704. continue;
  20705. }
  20706. if (!mesh.isReady()) {
  20707. return false;
  20708. }
  20709. // Highlight layers
  20710. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20711. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20712. var layer = _a[_i];
  20713. if (!layer.hasMesh(mesh)) {
  20714. continue;
  20715. }
  20716. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20717. var subMesh = _c[_b];
  20718. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20719. return false;
  20720. }
  20721. }
  20722. }
  20723. }
  20724. return true;
  20725. };
  20726. Scene.prototype.resetCachedMaterial = function () {
  20727. this._cachedMaterial = null;
  20728. this._cachedEffect = null;
  20729. this._cachedVisibility = null;
  20730. };
  20731. Scene.prototype.registerBeforeRender = function (func) {
  20732. this.onBeforeRenderObservable.add(func);
  20733. };
  20734. Scene.prototype.unregisterBeforeRender = function (func) {
  20735. this.onBeforeRenderObservable.removeCallback(func);
  20736. };
  20737. Scene.prototype.registerAfterRender = function (func) {
  20738. this.onAfterRenderObservable.add(func);
  20739. };
  20740. Scene.prototype.unregisterAfterRender = function (func) {
  20741. this.onAfterRenderObservable.removeCallback(func);
  20742. };
  20743. Scene.prototype._executeOnceBeforeRender = function (func) {
  20744. var _this = this;
  20745. var execFunc = function () {
  20746. func();
  20747. setTimeout(function () {
  20748. _this.unregisterBeforeRender(execFunc);
  20749. });
  20750. };
  20751. this.registerBeforeRender(execFunc);
  20752. };
  20753. /**
  20754. * The provided function will run before render once and will be disposed afterwards.
  20755. * A timeout delay can be provided so that the function will be executed in N ms.
  20756. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20757. * @param func The function to be executed.
  20758. * @param timeout optional delay in ms
  20759. */
  20760. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20761. var _this = this;
  20762. if (timeout !== undefined) {
  20763. setTimeout(function () {
  20764. _this._executeOnceBeforeRender(func);
  20765. }, timeout);
  20766. }
  20767. else {
  20768. this._executeOnceBeforeRender(func);
  20769. }
  20770. };
  20771. Scene.prototype._addPendingData = function (data) {
  20772. this._pendingData.push(data);
  20773. };
  20774. Scene.prototype._removePendingData = function (data) {
  20775. var wasLoading = this.isLoading;
  20776. var index = this._pendingData.indexOf(data);
  20777. if (index !== -1) {
  20778. this._pendingData.splice(index, 1);
  20779. }
  20780. if (wasLoading && !this.isLoading) {
  20781. this.onDataLoadedObservable.notifyObservers(this);
  20782. }
  20783. };
  20784. Scene.prototype.getWaitingItemsCount = function () {
  20785. return this._pendingData.length;
  20786. };
  20787. Object.defineProperty(Scene.prototype, "isLoading", {
  20788. get: function () {
  20789. return this._pendingData.length > 0;
  20790. },
  20791. enumerable: true,
  20792. configurable: true
  20793. });
  20794. /**
  20795. * Registers a function to be executed when the scene is ready.
  20796. * @param {Function} func - the function to be executed.
  20797. */
  20798. Scene.prototype.executeWhenReady = function (func) {
  20799. var _this = this;
  20800. this.onReadyObservable.add(func);
  20801. if (this._executeWhenReadyTimeoutId !== -1) {
  20802. return;
  20803. }
  20804. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20805. _this._checkIsReady();
  20806. }, 150);
  20807. };
  20808. Scene.prototype._checkIsReady = function () {
  20809. var _this = this;
  20810. if (this.isReady()) {
  20811. this.onReadyObservable.notifyObservers(this);
  20812. this.onReadyObservable.clear();
  20813. this._executeWhenReadyTimeoutId = -1;
  20814. return;
  20815. }
  20816. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20817. _this._checkIsReady();
  20818. }, 150);
  20819. };
  20820. // Animations
  20821. /**
  20822. * Will start the animation sequence of a given target
  20823. * @param target - the target
  20824. * @param {number} from - from which frame should animation start
  20825. * @param {number} to - till which frame should animation run.
  20826. * @param {boolean} [loop] - should the animation loop
  20827. * @param {number} [speedRatio] - the speed in which to run the animation
  20828. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20829. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20830. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20831. * See BABYLON.Animatable
  20832. */
  20833. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20834. if (speedRatio === void 0) { speedRatio = 1.0; }
  20835. if (from > to && speedRatio > 0) {
  20836. speedRatio *= -1;
  20837. }
  20838. this.stopAnimation(target);
  20839. if (!animatable) {
  20840. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20841. }
  20842. // Local animations
  20843. if (target.animations) {
  20844. animatable.appendAnimations(target, target.animations);
  20845. }
  20846. // Children animations
  20847. if (target.getAnimatables) {
  20848. var animatables = target.getAnimatables();
  20849. for (var index = 0; index < animatables.length; index++) {
  20850. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20851. }
  20852. }
  20853. animatable.reset();
  20854. return animatable;
  20855. };
  20856. /**
  20857. * Begin a new animation on a given node
  20858. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20859. * @param {BABYLON.Animation[]} defines the list of animations to start
  20860. * @param {number} from defines the initial value
  20861. * @param {number} to defines the final value
  20862. * @param {boolean} loop defines if you want animation to loop (off by default)
  20863. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20864. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20865. * @returns the list of created animatables
  20866. */
  20867. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20868. if (speedRatio === undefined) {
  20869. speedRatio = 1.0;
  20870. }
  20871. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20872. return animatable;
  20873. };
  20874. /**
  20875. * Begin a new animation on a given node and its hierarchy
  20876. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20877. * @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.
  20878. * @param {BABYLON.Animation[]} defines the list of animations to start
  20879. * @param {number} from defines the initial value
  20880. * @param {number} to defines the final value
  20881. * @param {boolean} loop defines if you want animation to loop (off by default)
  20882. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20883. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20884. * @returns the list of animatables created for all nodes
  20885. */
  20886. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20887. var children = target.getDescendants(directDescendantsOnly);
  20888. var result = [];
  20889. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20890. var child = children_1[_i];
  20891. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20892. }
  20893. return result;
  20894. };
  20895. Scene.prototype.getAnimatableByTarget = function (target) {
  20896. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20897. if (this._activeAnimatables[index].target === target) {
  20898. return this._activeAnimatables[index];
  20899. }
  20900. }
  20901. return null;
  20902. };
  20903. Object.defineProperty(Scene.prototype, "animatables", {
  20904. get: function () {
  20905. return this._activeAnimatables;
  20906. },
  20907. enumerable: true,
  20908. configurable: true
  20909. });
  20910. /**
  20911. * Will stop the animation of the given target
  20912. * @param target - the target
  20913. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20914. * @see beginAnimation
  20915. */
  20916. Scene.prototype.stopAnimation = function (target, animationName) {
  20917. var animatable = this.getAnimatableByTarget(target);
  20918. if (animatable) {
  20919. animatable.stop(animationName);
  20920. }
  20921. };
  20922. /**
  20923. * Stops and removes all animations that have been applied to the scene
  20924. */
  20925. Scene.prototype.stopAllAnimations = function () {
  20926. if (this._activeAnimatables) {
  20927. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20928. this._activeAnimatables[i].stop();
  20929. }
  20930. this._activeAnimatables = [];
  20931. }
  20932. };
  20933. Scene.prototype._animate = function () {
  20934. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20935. return;
  20936. }
  20937. // Getting time
  20938. var now = BABYLON.Tools.Now;
  20939. if (!this._animationTimeLast) {
  20940. if (this._pendingData.length > 0) {
  20941. return;
  20942. }
  20943. this._animationTimeLast = now;
  20944. }
  20945. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20946. this._animationTime += deltaTime;
  20947. this._animationTimeLast = now;
  20948. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20949. this._activeAnimatables[index]._animate(this._animationTime);
  20950. }
  20951. };
  20952. // Matrix
  20953. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20954. this._useAlternateCameraConfiguration = active;
  20955. };
  20956. Scene.prototype.getViewMatrix = function () {
  20957. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20958. };
  20959. Scene.prototype.getProjectionMatrix = function () {
  20960. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20961. };
  20962. Scene.prototype.getTransformMatrix = function () {
  20963. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20964. };
  20965. Scene.prototype.setTransformMatrix = function (view, projection) {
  20966. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20967. return;
  20968. }
  20969. this._viewUpdateFlag = view.updateFlag;
  20970. this._projectionUpdateFlag = projection.updateFlag;
  20971. this._viewMatrix = view;
  20972. this._projectionMatrix = projection;
  20973. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20974. // Update frustum
  20975. if (!this._frustumPlanes) {
  20976. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20977. }
  20978. else {
  20979. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20980. }
  20981. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20982. var otherCamera = this.activeCamera._alternateCamera;
  20983. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20984. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20985. }
  20986. if (this._sceneUbo.useUbo) {
  20987. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20988. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20989. this._sceneUbo.update();
  20990. }
  20991. };
  20992. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20993. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20994. return;
  20995. }
  20996. this._alternateViewUpdateFlag = view.updateFlag;
  20997. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20998. this._alternateViewMatrix = view;
  20999. this._alternateProjectionMatrix = projection;
  21000. if (!this._alternateTransformMatrix) {
  21001. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21002. }
  21003. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21004. if (!this._alternateSceneUbo) {
  21005. this._createAlternateUbo();
  21006. }
  21007. if (this._alternateSceneUbo.useUbo) {
  21008. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21009. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21010. this._alternateSceneUbo.update();
  21011. }
  21012. };
  21013. Scene.prototype.getSceneUniformBuffer = function () {
  21014. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21015. };
  21016. // Methods
  21017. Scene.prototype.getUniqueId = function () {
  21018. var result = Scene._uniqueIdCounter;
  21019. Scene._uniqueIdCounter++;
  21020. return result;
  21021. };
  21022. Scene.prototype.addMesh = function (newMesh) {
  21023. this.meshes.push(newMesh);
  21024. //notify the collision coordinator
  21025. if (this.collisionCoordinator) {
  21026. this.collisionCoordinator.onMeshAdded(newMesh);
  21027. }
  21028. newMesh._resyncLightSources();
  21029. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21030. };
  21031. Scene.prototype.removeMesh = function (toRemove) {
  21032. var index = this.meshes.indexOf(toRemove);
  21033. if (index !== -1) {
  21034. // Remove from the scene if mesh found
  21035. this.meshes.splice(index, 1);
  21036. }
  21037. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21038. return index;
  21039. };
  21040. Scene.prototype.addTransformNode = function (newTransformNode) {
  21041. this.transformNodes.push(newTransformNode);
  21042. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21043. };
  21044. Scene.prototype.removeTransformNode = function (toRemove) {
  21045. var index = this.transformNodes.indexOf(toRemove);
  21046. if (index !== -1) {
  21047. // Remove from the scene if found
  21048. this.transformNodes.splice(index, 1);
  21049. }
  21050. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21051. return index;
  21052. };
  21053. Scene.prototype.removeSkeleton = function (toRemove) {
  21054. var index = this.skeletons.indexOf(toRemove);
  21055. if (index !== -1) {
  21056. // Remove from the scene if found
  21057. this.skeletons.splice(index, 1);
  21058. }
  21059. return index;
  21060. };
  21061. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21062. var index = this.morphTargetManagers.indexOf(toRemove);
  21063. if (index !== -1) {
  21064. // Remove from the scene if found
  21065. this.morphTargetManagers.splice(index, 1);
  21066. }
  21067. return index;
  21068. };
  21069. Scene.prototype.removeLight = function (toRemove) {
  21070. var index = this.lights.indexOf(toRemove);
  21071. if (index !== -1) {
  21072. // Remove from meshes
  21073. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21074. var mesh = _a[_i];
  21075. mesh._removeLightSource(toRemove);
  21076. }
  21077. // Remove from the scene if mesh found
  21078. this.lights.splice(index, 1);
  21079. this.sortLightsByPriority();
  21080. }
  21081. this.onLightRemovedObservable.notifyObservers(toRemove);
  21082. return index;
  21083. };
  21084. Scene.prototype.removeCamera = function (toRemove) {
  21085. var index = this.cameras.indexOf(toRemove);
  21086. if (index !== -1) {
  21087. // Remove from the scene if mesh found
  21088. this.cameras.splice(index, 1);
  21089. }
  21090. // Remove from activeCameras
  21091. var index2 = this.activeCameras.indexOf(toRemove);
  21092. if (index2 !== -1) {
  21093. // Remove from the scene if mesh found
  21094. this.activeCameras.splice(index2, 1);
  21095. }
  21096. // Reset the activeCamera
  21097. if (this.activeCamera === toRemove) {
  21098. if (this.cameras.length > 0) {
  21099. this.activeCamera = this.cameras[0];
  21100. }
  21101. else {
  21102. this.activeCamera = null;
  21103. }
  21104. }
  21105. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21106. return index;
  21107. };
  21108. Scene.prototype.removeParticleSystem = function (toRemove) {
  21109. var index = this.particleSystems.indexOf(toRemove);
  21110. if (index !== -1) {
  21111. this.particleSystems.splice(index, 1);
  21112. }
  21113. return index;
  21114. };
  21115. ;
  21116. Scene.prototype.removeAnimation = function (toRemove) {
  21117. var index = this.animations.indexOf(toRemove);
  21118. if (index !== -1) {
  21119. this.animations.splice(index, 1);
  21120. }
  21121. return index;
  21122. };
  21123. ;
  21124. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21125. var index = this.multiMaterials.indexOf(toRemove);
  21126. if (index !== -1) {
  21127. this.multiMaterials.splice(index, 1);
  21128. }
  21129. return index;
  21130. };
  21131. ;
  21132. Scene.prototype.removeMaterial = function (toRemove) {
  21133. var index = this.materials.indexOf(toRemove);
  21134. if (index !== -1) {
  21135. this.materials.splice(index, 1);
  21136. }
  21137. return index;
  21138. };
  21139. ;
  21140. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21141. var index = this.lensFlareSystems.indexOf(toRemove);
  21142. if (index !== -1) {
  21143. this.lensFlareSystems.splice(index, 1);
  21144. }
  21145. return index;
  21146. };
  21147. ;
  21148. Scene.prototype.removeActionManager = function (toRemove) {
  21149. var index = this._actionManagers.indexOf(toRemove);
  21150. if (index !== -1) {
  21151. this._actionManagers.splice(index, 1);
  21152. }
  21153. return index;
  21154. };
  21155. ;
  21156. Scene.prototype.addLight = function (newLight) {
  21157. this.lights.push(newLight);
  21158. this.sortLightsByPriority();
  21159. // Add light to all meshes (To support if the light is removed and then readded)
  21160. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21161. var mesh = _a[_i];
  21162. if (mesh._lightSources.indexOf(newLight) === -1) {
  21163. mesh._lightSources.push(newLight);
  21164. mesh._resyncLightSources();
  21165. }
  21166. }
  21167. this.onNewLightAddedObservable.notifyObservers(newLight);
  21168. };
  21169. Scene.prototype.sortLightsByPriority = function () {
  21170. if (this.requireLightSorting) {
  21171. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21172. }
  21173. };
  21174. Scene.prototype.addCamera = function (newCamera) {
  21175. this.cameras.push(newCamera);
  21176. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21177. };
  21178. Scene.prototype.addSkeleton = function (newSkeleton) {
  21179. this.skeletons.push(newSkeleton);
  21180. };
  21181. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21182. this.particleSystems.push(newParticleSystem);
  21183. };
  21184. Scene.prototype.addAnimation = function (newAnimation) {
  21185. this.animations.push(newAnimation);
  21186. };
  21187. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21188. this.multiMaterials.push(newMultiMaterial);
  21189. };
  21190. Scene.prototype.addMaterial = function (newMaterial) {
  21191. this.materials.push(newMaterial);
  21192. };
  21193. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21194. this.morphTargetManagers.push(newMorphTargetManager);
  21195. };
  21196. Scene.prototype.addGeometry = function (newGeometrie) {
  21197. this._geometries.push(newGeometrie);
  21198. };
  21199. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21200. this.lensFlareSystems.push(newLensFlareSystem);
  21201. };
  21202. Scene.prototype.addActionManager = function (newActionManager) {
  21203. this._actionManagers.push(newActionManager);
  21204. };
  21205. /**
  21206. * Switch active camera
  21207. * @param {Camera} newCamera - new active camera
  21208. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21209. */
  21210. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21211. if (attachControl === void 0) { attachControl = true; }
  21212. var canvas = this._engine.getRenderingCanvas();
  21213. if (!canvas) {
  21214. return;
  21215. }
  21216. if (this.activeCamera) {
  21217. this.activeCamera.detachControl(canvas);
  21218. }
  21219. this.activeCamera = newCamera;
  21220. if (attachControl) {
  21221. newCamera.attachControl(canvas);
  21222. }
  21223. };
  21224. /**
  21225. * sets the active camera of the scene using its ID
  21226. * @param {string} id - the camera's ID
  21227. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21228. * @see activeCamera
  21229. */
  21230. Scene.prototype.setActiveCameraByID = function (id) {
  21231. var camera = this.getCameraByID(id);
  21232. if (camera) {
  21233. this.activeCamera = camera;
  21234. return camera;
  21235. }
  21236. return null;
  21237. };
  21238. /**
  21239. * sets the active camera of the scene using its name
  21240. * @param {string} name - the camera's name
  21241. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21242. * @see activeCamera
  21243. */
  21244. Scene.prototype.setActiveCameraByName = function (name) {
  21245. var camera = this.getCameraByName(name);
  21246. if (camera) {
  21247. this.activeCamera = camera;
  21248. return camera;
  21249. }
  21250. return null;
  21251. };
  21252. /**
  21253. * get an animation group using its name
  21254. * @param {string} the material's name
  21255. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21256. */
  21257. Scene.prototype.getAnimationGroupByName = function (name) {
  21258. for (var index = 0; index < this.animationGroups.length; index++) {
  21259. if (this.animationGroups[index].name === name) {
  21260. return this.animationGroups[index];
  21261. }
  21262. }
  21263. return null;
  21264. };
  21265. /**
  21266. * get a material using its id
  21267. * @param {string} the material's ID
  21268. * @return {BABYLON.Material|null} the material or null if none found.
  21269. */
  21270. Scene.prototype.getMaterialByID = function (id) {
  21271. for (var index = 0; index < this.materials.length; index++) {
  21272. if (this.materials[index].id === id) {
  21273. return this.materials[index];
  21274. }
  21275. }
  21276. return null;
  21277. };
  21278. /**
  21279. * get a material using its name
  21280. * @param {string} the material's name
  21281. * @return {BABYLON.Material|null} the material or null if none found.
  21282. */
  21283. Scene.prototype.getMaterialByName = function (name) {
  21284. for (var index = 0; index < this.materials.length; index++) {
  21285. if (this.materials[index].name === name) {
  21286. return this.materials[index];
  21287. }
  21288. }
  21289. return null;
  21290. };
  21291. Scene.prototype.getLensFlareSystemByName = function (name) {
  21292. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21293. if (this.lensFlareSystems[index].name === name) {
  21294. return this.lensFlareSystems[index];
  21295. }
  21296. }
  21297. return null;
  21298. };
  21299. Scene.prototype.getLensFlareSystemByID = function (id) {
  21300. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21301. if (this.lensFlareSystems[index].id === id) {
  21302. return this.lensFlareSystems[index];
  21303. }
  21304. }
  21305. return null;
  21306. };
  21307. Scene.prototype.getCameraByID = function (id) {
  21308. for (var index = 0; index < this.cameras.length; index++) {
  21309. if (this.cameras[index].id === id) {
  21310. return this.cameras[index];
  21311. }
  21312. }
  21313. return null;
  21314. };
  21315. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21316. for (var index = 0; index < this.cameras.length; index++) {
  21317. if (this.cameras[index].uniqueId === uniqueId) {
  21318. return this.cameras[index];
  21319. }
  21320. }
  21321. return null;
  21322. };
  21323. /**
  21324. * get a camera using its name
  21325. * @param {string} the camera's name
  21326. * @return {BABYLON.Camera|null} the camera or null if none found.
  21327. */
  21328. Scene.prototype.getCameraByName = function (name) {
  21329. for (var index = 0; index < this.cameras.length; index++) {
  21330. if (this.cameras[index].name === name) {
  21331. return this.cameras[index];
  21332. }
  21333. }
  21334. return null;
  21335. };
  21336. /**
  21337. * get a bone using its id
  21338. * @param {string} the bone's id
  21339. * @return {BABYLON.Bone|null} the bone or null if not found
  21340. */
  21341. Scene.prototype.getBoneByID = function (id) {
  21342. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21343. var skeleton = this.skeletons[skeletonIndex];
  21344. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21345. if (skeleton.bones[boneIndex].id === id) {
  21346. return skeleton.bones[boneIndex];
  21347. }
  21348. }
  21349. }
  21350. return null;
  21351. };
  21352. /**
  21353. * get a bone using its id
  21354. * @param {string} the bone's name
  21355. * @return {BABYLON.Bone|null} the bone or null if not found
  21356. */
  21357. Scene.prototype.getBoneByName = function (name) {
  21358. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21359. var skeleton = this.skeletons[skeletonIndex];
  21360. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21361. if (skeleton.bones[boneIndex].name === name) {
  21362. return skeleton.bones[boneIndex];
  21363. }
  21364. }
  21365. }
  21366. return null;
  21367. };
  21368. /**
  21369. * get a light node using its name
  21370. * @param {string} the light's name
  21371. * @return {BABYLON.Light|null} the light or null if none found.
  21372. */
  21373. Scene.prototype.getLightByName = function (name) {
  21374. for (var index = 0; index < this.lights.length; index++) {
  21375. if (this.lights[index].name === name) {
  21376. return this.lights[index];
  21377. }
  21378. }
  21379. return null;
  21380. };
  21381. /**
  21382. * get a light node using its ID
  21383. * @param {string} the light's id
  21384. * @return {BABYLON.Light|null} the light or null if none found.
  21385. */
  21386. Scene.prototype.getLightByID = function (id) {
  21387. for (var index = 0; index < this.lights.length; index++) {
  21388. if (this.lights[index].id === id) {
  21389. return this.lights[index];
  21390. }
  21391. }
  21392. return null;
  21393. };
  21394. /**
  21395. * get a light node using its scene-generated unique ID
  21396. * @param {number} the light's unique id
  21397. * @return {BABYLON.Light|null} the light or null if none found.
  21398. */
  21399. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21400. for (var index = 0; index < this.lights.length; index++) {
  21401. if (this.lights[index].uniqueId === uniqueId) {
  21402. return this.lights[index];
  21403. }
  21404. }
  21405. return null;
  21406. };
  21407. /**
  21408. * get a particle system by id
  21409. * @param id {number} the particle system id
  21410. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21411. */
  21412. Scene.prototype.getParticleSystemByID = function (id) {
  21413. for (var index = 0; index < this.particleSystems.length; index++) {
  21414. if (this.particleSystems[index].id === id) {
  21415. return this.particleSystems[index];
  21416. }
  21417. }
  21418. return null;
  21419. };
  21420. /**
  21421. * get a geometry using its ID
  21422. * @param {string} the geometry's id
  21423. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21424. */
  21425. Scene.prototype.getGeometryByID = function (id) {
  21426. for (var index = 0; index < this._geometries.length; index++) {
  21427. if (this._geometries[index].id === id) {
  21428. return this._geometries[index];
  21429. }
  21430. }
  21431. return null;
  21432. };
  21433. /**
  21434. * add a new geometry to this scene.
  21435. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21436. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21437. * @return {boolean} was the geometry added or not
  21438. */
  21439. Scene.prototype.pushGeometry = function (geometry, force) {
  21440. if (!force && this.getGeometryByID(geometry.id)) {
  21441. return false;
  21442. }
  21443. this._geometries.push(geometry);
  21444. //notify the collision coordinator
  21445. if (this.collisionCoordinator) {
  21446. this.collisionCoordinator.onGeometryAdded(geometry);
  21447. }
  21448. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21449. return true;
  21450. };
  21451. /**
  21452. * Removes an existing geometry
  21453. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21454. * @return {boolean} was the geometry removed or not
  21455. */
  21456. Scene.prototype.removeGeometry = function (geometry) {
  21457. var index = this._geometries.indexOf(geometry);
  21458. if (index > -1) {
  21459. this._geometries.splice(index, 1);
  21460. //notify the collision coordinator
  21461. if (this.collisionCoordinator) {
  21462. this.collisionCoordinator.onGeometryDeleted(geometry);
  21463. }
  21464. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21465. return true;
  21466. }
  21467. return false;
  21468. };
  21469. Scene.prototype.getGeometries = function () {
  21470. return this._geometries;
  21471. };
  21472. /**
  21473. * Get the first added mesh found of a given ID
  21474. * @param {string} id - the id to search for
  21475. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21476. */
  21477. Scene.prototype.getMeshByID = function (id) {
  21478. for (var index = 0; index < this.meshes.length; index++) {
  21479. if (this.meshes[index].id === id) {
  21480. return this.meshes[index];
  21481. }
  21482. }
  21483. return null;
  21484. };
  21485. Scene.prototype.getMeshesByID = function (id) {
  21486. return this.meshes.filter(function (m) {
  21487. return m.id === id;
  21488. });
  21489. };
  21490. /**
  21491. * Get the first added transform node found of a given ID
  21492. * @param {string} id - the id to search for
  21493. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21494. */
  21495. Scene.prototype.getTransformNodeByID = function (id) {
  21496. for (var index = 0; index < this.transformNodes.length; index++) {
  21497. if (this.transformNodes[index].id === id) {
  21498. return this.transformNodes[index];
  21499. }
  21500. }
  21501. return null;
  21502. };
  21503. Scene.prototype.getTransformNodesByID = function (id) {
  21504. return this.transformNodes.filter(function (m) {
  21505. return m.id === id;
  21506. });
  21507. };
  21508. /**
  21509. * Get a mesh with its auto-generated unique id
  21510. * @param {number} uniqueId - the unique id to search for
  21511. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21512. */
  21513. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21514. for (var index = 0; index < this.meshes.length; index++) {
  21515. if (this.meshes[index].uniqueId === uniqueId) {
  21516. return this.meshes[index];
  21517. }
  21518. }
  21519. return null;
  21520. };
  21521. /**
  21522. * Get a the last added mesh found of a given ID
  21523. * @param {string} id - the id to search for
  21524. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21525. */
  21526. Scene.prototype.getLastMeshByID = function (id) {
  21527. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21528. if (this.meshes[index].id === id) {
  21529. return this.meshes[index];
  21530. }
  21531. }
  21532. return null;
  21533. };
  21534. /**
  21535. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21536. * @param {string} id - the id to search for
  21537. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21538. */
  21539. Scene.prototype.getLastEntryByID = function (id) {
  21540. var index;
  21541. for (index = this.meshes.length - 1; index >= 0; index--) {
  21542. if (this.meshes[index].id === id) {
  21543. return this.meshes[index];
  21544. }
  21545. }
  21546. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21547. if (this.transformNodes[index].id === id) {
  21548. return this.transformNodes[index];
  21549. }
  21550. }
  21551. for (index = this.cameras.length - 1; index >= 0; index--) {
  21552. if (this.cameras[index].id === id) {
  21553. return this.cameras[index];
  21554. }
  21555. }
  21556. for (index = this.lights.length - 1; index >= 0; index--) {
  21557. if (this.lights[index].id === id) {
  21558. return this.lights[index];
  21559. }
  21560. }
  21561. return null;
  21562. };
  21563. Scene.prototype.getNodeByID = function (id) {
  21564. var mesh = this.getMeshByID(id);
  21565. if (mesh) {
  21566. return mesh;
  21567. }
  21568. var light = this.getLightByID(id);
  21569. if (light) {
  21570. return light;
  21571. }
  21572. var camera = this.getCameraByID(id);
  21573. if (camera) {
  21574. return camera;
  21575. }
  21576. var bone = this.getBoneByID(id);
  21577. return bone;
  21578. };
  21579. Scene.prototype.getNodeByName = function (name) {
  21580. var mesh = this.getMeshByName(name);
  21581. if (mesh) {
  21582. return mesh;
  21583. }
  21584. var light = this.getLightByName(name);
  21585. if (light) {
  21586. return light;
  21587. }
  21588. var camera = this.getCameraByName(name);
  21589. if (camera) {
  21590. return camera;
  21591. }
  21592. var bone = this.getBoneByName(name);
  21593. return bone;
  21594. };
  21595. Scene.prototype.getMeshByName = function (name) {
  21596. for (var index = 0; index < this.meshes.length; index++) {
  21597. if (this.meshes[index].name === name) {
  21598. return this.meshes[index];
  21599. }
  21600. }
  21601. return null;
  21602. };
  21603. Scene.prototype.getTransformNodeByName = function (name) {
  21604. for (var index = 0; index < this.transformNodes.length; index++) {
  21605. if (this.transformNodes[index].name === name) {
  21606. return this.transformNodes[index];
  21607. }
  21608. }
  21609. return null;
  21610. };
  21611. Scene.prototype.getSoundByName = function (name) {
  21612. var index;
  21613. if (BABYLON.AudioEngine) {
  21614. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21615. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21616. return this.mainSoundTrack.soundCollection[index];
  21617. }
  21618. }
  21619. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21620. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21621. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21622. return this.soundTracks[sdIndex].soundCollection[index];
  21623. }
  21624. }
  21625. }
  21626. }
  21627. return null;
  21628. };
  21629. Scene.prototype.getLastSkeletonByID = function (id) {
  21630. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21631. if (this.skeletons[index].id === id) {
  21632. return this.skeletons[index];
  21633. }
  21634. }
  21635. return null;
  21636. };
  21637. Scene.prototype.getSkeletonById = function (id) {
  21638. for (var index = 0; index < this.skeletons.length; index++) {
  21639. if (this.skeletons[index].id === id) {
  21640. return this.skeletons[index];
  21641. }
  21642. }
  21643. return null;
  21644. };
  21645. Scene.prototype.getSkeletonByName = function (name) {
  21646. for (var index = 0; index < this.skeletons.length; index++) {
  21647. if (this.skeletons[index].name === name) {
  21648. return this.skeletons[index];
  21649. }
  21650. }
  21651. return null;
  21652. };
  21653. Scene.prototype.getMorphTargetManagerById = function (id) {
  21654. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21655. if (this.morphTargetManagers[index].uniqueId === id) {
  21656. return this.morphTargetManagers[index];
  21657. }
  21658. }
  21659. return null;
  21660. };
  21661. Scene.prototype.isActiveMesh = function (mesh) {
  21662. return (this._activeMeshes.indexOf(mesh) !== -1);
  21663. };
  21664. /**
  21665. * Return a the first highlight layer of the scene with a given name.
  21666. * @param name The name of the highlight layer to look for.
  21667. * @return The highlight layer if found otherwise null.
  21668. */
  21669. Scene.prototype.getHighlightLayerByName = function (name) {
  21670. for (var index = 0; index < this.highlightLayers.length; index++) {
  21671. if (this.highlightLayers[index].name === name) {
  21672. return this.highlightLayers[index];
  21673. }
  21674. }
  21675. return null;
  21676. };
  21677. Object.defineProperty(Scene.prototype, "uid", {
  21678. /**
  21679. * Return a unique id as a string which can serve as an identifier for the scene
  21680. */
  21681. get: function () {
  21682. if (!this._uid) {
  21683. this._uid = BABYLON.Tools.RandomId();
  21684. }
  21685. return this._uid;
  21686. },
  21687. enumerable: true,
  21688. configurable: true
  21689. });
  21690. /**
  21691. * Add an externaly attached data from its key.
  21692. * This method call will fail and return false, if such key already exists.
  21693. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21694. * @param key the unique key that identifies the data
  21695. * @param data the data object to associate to the key for this Engine instance
  21696. * @return true if no such key were already present and the data was added successfully, false otherwise
  21697. */
  21698. Scene.prototype.addExternalData = function (key, data) {
  21699. if (!this._externalData) {
  21700. this._externalData = new BABYLON.StringDictionary();
  21701. }
  21702. return this._externalData.add(key, data);
  21703. };
  21704. /**
  21705. * Get an externaly attached data from its key
  21706. * @param key the unique key that identifies the data
  21707. * @return the associated data, if present (can be null), or undefined if not present
  21708. */
  21709. Scene.prototype.getExternalData = function (key) {
  21710. if (!this._externalData) {
  21711. return null;
  21712. }
  21713. return this._externalData.get(key);
  21714. };
  21715. /**
  21716. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21717. * @param key the unique key that identifies the data
  21718. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21719. * @return the associated data, can be null if the factory returned null.
  21720. */
  21721. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21722. if (!this._externalData) {
  21723. this._externalData = new BABYLON.StringDictionary();
  21724. }
  21725. return this._externalData.getOrAddWithFactory(key, factory);
  21726. };
  21727. /**
  21728. * Remove an externaly attached data from the Engine instance
  21729. * @param key the unique key that identifies the data
  21730. * @return true if the data was successfully removed, false if it doesn't exist
  21731. */
  21732. Scene.prototype.removeExternalData = function (key) {
  21733. return this._externalData.remove(key);
  21734. };
  21735. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21736. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21737. if (mesh.showSubMeshesBoundingBox) {
  21738. var boundingInfo = subMesh.getBoundingInfo();
  21739. if (boundingInfo !== null && boundingInfo !== undefined) {
  21740. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21741. }
  21742. }
  21743. var material = subMesh.getMaterial();
  21744. if (material !== null && material !== undefined) {
  21745. // Render targets
  21746. if (material.getRenderTargetTextures !== undefined) {
  21747. if (this._processedMaterials.indexOf(material) === -1) {
  21748. this._processedMaterials.push(material);
  21749. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21750. }
  21751. }
  21752. // Dispatch
  21753. this._activeIndices.addCount(subMesh.indexCount, false);
  21754. this._renderingManager.dispatch(subMesh, mesh, material);
  21755. }
  21756. }
  21757. };
  21758. Scene.prototype._isInIntermediateRendering = function () {
  21759. return this._intermediateRendering;
  21760. };
  21761. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21762. this._activeMeshCandidateProvider = provider;
  21763. };
  21764. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21765. return this._activeMeshCandidateProvider;
  21766. };
  21767. /**
  21768. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21769. */
  21770. Scene.prototype.freezeActiveMeshes = function () {
  21771. this._evaluateActiveMeshes();
  21772. this._activeMeshesFrozen = true;
  21773. return this;
  21774. };
  21775. /**
  21776. * Use this function to restart evaluating active meshes on every frame
  21777. */
  21778. Scene.prototype.unfreezeActiveMeshes = function () {
  21779. this._activeMeshesFrozen = false;
  21780. return this;
  21781. };
  21782. Scene.prototype._evaluateActiveMeshes = function () {
  21783. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21784. return;
  21785. }
  21786. if (!this.activeCamera) {
  21787. return;
  21788. }
  21789. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21790. this.activeCamera._activeMeshes.reset();
  21791. this._activeMeshes.reset();
  21792. this._renderingManager.reset();
  21793. this._processedMaterials.reset();
  21794. this._activeParticleSystems.reset();
  21795. this._activeSkeletons.reset();
  21796. this._softwareSkinnedMeshes.reset();
  21797. if (this._boundingBoxRenderer) {
  21798. this._boundingBoxRenderer.reset();
  21799. }
  21800. // Meshes
  21801. var meshes;
  21802. var len;
  21803. var checkIsEnabled = true;
  21804. // Determine mesh candidates
  21805. if (this._activeMeshCandidateProvider !== undefined) {
  21806. // Use _activeMeshCandidateProvider
  21807. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21808. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21809. if (meshes !== undefined) {
  21810. len = meshes.length;
  21811. }
  21812. else {
  21813. len = 0;
  21814. }
  21815. }
  21816. else if (this._selectionOctree !== undefined) {
  21817. // Octree
  21818. var selection = this._selectionOctree.select(this._frustumPlanes);
  21819. meshes = selection.data;
  21820. len = selection.length;
  21821. }
  21822. else {
  21823. // Full scene traversal
  21824. len = this.meshes.length;
  21825. meshes = this.meshes;
  21826. }
  21827. // Check each mesh
  21828. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21829. mesh = meshes[meshIndex];
  21830. if (mesh.isBlocked) {
  21831. continue;
  21832. }
  21833. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21834. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21835. continue;
  21836. }
  21837. mesh.computeWorldMatrix();
  21838. // Intersections
  21839. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21840. this._meshesForIntersections.pushNoDuplicate(mesh);
  21841. }
  21842. // Switch to current LOD
  21843. meshLOD = mesh.getLOD(this.activeCamera);
  21844. if (meshLOD === undefined || meshLOD === null) {
  21845. continue;
  21846. }
  21847. mesh._preActivate();
  21848. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21849. this._activeMeshes.push(mesh);
  21850. this.activeCamera._activeMeshes.push(mesh);
  21851. mesh._activate(this._renderId);
  21852. if (meshLOD !== mesh) {
  21853. meshLOD._activate(this._renderId);
  21854. }
  21855. this._activeMesh(mesh, meshLOD);
  21856. }
  21857. }
  21858. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21859. // Particle systems
  21860. if (this.particlesEnabled) {
  21861. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21862. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21863. var particleSystem = this.particleSystems[particleIndex];
  21864. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21865. continue;
  21866. }
  21867. var emitter = particleSystem.emitter;
  21868. if (!emitter.position || emitter.isEnabled()) {
  21869. this._activeParticleSystems.push(particleSystem);
  21870. particleSystem.animate();
  21871. this._renderingManager.dispatchParticles(particleSystem);
  21872. }
  21873. }
  21874. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21875. }
  21876. };
  21877. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21878. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21879. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21880. mesh.skeleton.prepare();
  21881. }
  21882. if (!mesh.computeBonesUsingShaders) {
  21883. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21884. }
  21885. }
  21886. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21887. var boundingInfo = sourceMesh.getBoundingInfo();
  21888. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21889. }
  21890. if (mesh !== undefined && mesh !== null
  21891. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21892. // Submeshes Octrees
  21893. var len;
  21894. var subMeshes;
  21895. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21896. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21897. len = intersections.length;
  21898. subMeshes = intersections.data;
  21899. }
  21900. else {
  21901. subMeshes = mesh.subMeshes;
  21902. len = subMeshes.length;
  21903. }
  21904. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21905. subMesh = subMeshes[subIndex];
  21906. this._evaluateSubMesh(subMesh, mesh);
  21907. }
  21908. }
  21909. };
  21910. Scene.prototype.updateTransformMatrix = function (force) {
  21911. if (!this.activeCamera) {
  21912. return;
  21913. }
  21914. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21915. };
  21916. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21917. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21918. };
  21919. Scene.prototype._renderForCamera = function (camera) {
  21920. if (camera && camera._skipRendering) {
  21921. return;
  21922. }
  21923. var engine = this._engine;
  21924. this.activeCamera = camera;
  21925. if (!this.activeCamera)
  21926. throw new Error("Active camera not set");
  21927. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21928. // Viewport
  21929. engine.setViewport(this.activeCamera.viewport);
  21930. // Camera
  21931. this.resetCachedMaterial();
  21932. this._renderId++;
  21933. this.activeCamera.update();
  21934. this.updateTransformMatrix();
  21935. if (camera._alternateCamera) {
  21936. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21937. this._alternateRendering = true;
  21938. }
  21939. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21940. // Meshes
  21941. this._evaluateActiveMeshes();
  21942. // Software skinning
  21943. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21944. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21945. mesh.applySkeleton(mesh.skeleton);
  21946. }
  21947. // Render targets
  21948. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21949. var needsRestoreFrameBuffer = false;
  21950. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21951. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21952. }
  21953. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21954. this._intermediateRendering = true;
  21955. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21956. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21957. var renderTarget = this._renderTargets.data[renderIndex];
  21958. if (renderTarget._shouldRender()) {
  21959. this._renderId++;
  21960. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21961. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21962. }
  21963. }
  21964. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21965. this._intermediateRendering = false;
  21966. this._renderId++;
  21967. needsRestoreFrameBuffer = true; // Restore back buffer
  21968. }
  21969. // Render HighlightLayer Texture
  21970. var stencilState = this._engine.getStencilBuffer();
  21971. var renderhighlights = false;
  21972. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21973. this._intermediateRendering = true;
  21974. for (var i = 0; i < this.highlightLayers.length; i++) {
  21975. var highlightLayer = this.highlightLayers[i];
  21976. if (highlightLayer.shouldRender() &&
  21977. (!highlightLayer.camera ||
  21978. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21979. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21980. renderhighlights = true;
  21981. var renderTarget = highlightLayer._mainTexture;
  21982. if (renderTarget._shouldRender()) {
  21983. this._renderId++;
  21984. renderTarget.render(false, false);
  21985. needsRestoreFrameBuffer = true;
  21986. }
  21987. }
  21988. }
  21989. this._intermediateRendering = false;
  21990. this._renderId++;
  21991. }
  21992. if (needsRestoreFrameBuffer) {
  21993. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21994. }
  21995. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21996. // Prepare Frame
  21997. this.postProcessManager._prepareFrame();
  21998. // Backgrounds
  21999. var layerIndex;
  22000. var layer;
  22001. if (this.layers.length) {
  22002. engine.setDepthBuffer(false);
  22003. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22004. layer = this.layers[layerIndex];
  22005. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22006. layer.render();
  22007. }
  22008. }
  22009. engine.setDepthBuffer(true);
  22010. }
  22011. // Activate HighlightLayer stencil
  22012. if (renderhighlights) {
  22013. this._engine.setStencilBuffer(true);
  22014. }
  22015. // Render
  22016. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22017. this._renderingManager.render(null, null, true, true);
  22018. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22019. // Restore HighlightLayer stencil
  22020. if (renderhighlights) {
  22021. this._engine.setStencilBuffer(stencilState);
  22022. }
  22023. // Bounding boxes
  22024. if (this._boundingBoxRenderer) {
  22025. this._boundingBoxRenderer.render();
  22026. }
  22027. // Lens flares
  22028. if (this.lensFlaresEnabled) {
  22029. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22030. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22031. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22032. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22033. lensFlareSystem.render();
  22034. }
  22035. }
  22036. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22037. }
  22038. // Foregrounds
  22039. if (this.layers.length) {
  22040. engine.setDepthBuffer(false);
  22041. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22042. layer = this.layers[layerIndex];
  22043. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22044. layer.render();
  22045. }
  22046. }
  22047. engine.setDepthBuffer(true);
  22048. }
  22049. // Highlight Layer
  22050. if (renderhighlights) {
  22051. engine.setDepthBuffer(false);
  22052. for (var i = 0; i < this.highlightLayers.length; i++) {
  22053. if (this.highlightLayers[i].shouldRender()) {
  22054. this.highlightLayers[i].render();
  22055. }
  22056. }
  22057. engine.setDepthBuffer(true);
  22058. }
  22059. // Finalize frame
  22060. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22061. // Reset some special arrays
  22062. this._renderTargets.reset();
  22063. this._alternateRendering = false;
  22064. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22065. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22066. };
  22067. Scene.prototype._processSubCameras = function (camera) {
  22068. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22069. this._renderForCamera(camera);
  22070. return;
  22071. }
  22072. // Update camera
  22073. if (this.activeCamera) {
  22074. this.activeCamera.update();
  22075. }
  22076. // rig cameras
  22077. for (var index = 0; index < camera._rigCameras.length; index++) {
  22078. this._renderForCamera(camera._rigCameras[index]);
  22079. }
  22080. this.activeCamera = camera;
  22081. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22082. };
  22083. Scene.prototype._checkIntersections = function () {
  22084. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22085. var sourceMesh = this._meshesForIntersections.data[index];
  22086. if (!sourceMesh.actionManager) {
  22087. continue;
  22088. }
  22089. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22090. var action = sourceMesh.actionManager.actions[actionIndex];
  22091. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22092. var parameters = action.getTriggerParameter();
  22093. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22094. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22095. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22096. if (areIntersecting && currentIntersectionInProgress === -1) {
  22097. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22098. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22099. sourceMesh._intersectionsInProgress.push(otherMesh);
  22100. }
  22101. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22102. sourceMesh._intersectionsInProgress.push(otherMesh);
  22103. }
  22104. }
  22105. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22106. //They intersected, and now they don't.
  22107. //is this trigger an exit trigger? execute an event.
  22108. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22109. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22110. }
  22111. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22112. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22113. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22114. }
  22115. }
  22116. }
  22117. }
  22118. }
  22119. };
  22120. Scene.prototype.render = function () {
  22121. if (this.isDisposed) {
  22122. return;
  22123. }
  22124. this._activeParticles.fetchNewFrame();
  22125. this._totalVertices.fetchNewFrame();
  22126. this._activeIndices.fetchNewFrame();
  22127. this._activeBones.fetchNewFrame();
  22128. this._meshesForIntersections.reset();
  22129. this.resetCachedMaterial();
  22130. this.onBeforeAnimationsObservable.notifyObservers(this);
  22131. // Actions
  22132. if (this.actionManager) {
  22133. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22134. }
  22135. //Simplification Queue
  22136. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22137. this.simplificationQueue.executeNext();
  22138. }
  22139. if (this._engine.isDeterministicLockStep()) {
  22140. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22141. var defaultFPS = (60.0 / 1000.0);
  22142. var defaultFrameTime = 1000 / 60; // frame time in MS
  22143. if (this._physicsEngine) {
  22144. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22145. }
  22146. var stepsTaken = 0;
  22147. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22148. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22149. internalSteps = Math.min(internalSteps, maxSubSteps);
  22150. do {
  22151. this.onBeforeStepObservable.notifyObservers(this);
  22152. // Animations
  22153. this._animationRatio = defaultFrameTime * defaultFPS;
  22154. this._animate();
  22155. this.onAfterAnimationsObservable.notifyObservers(this);
  22156. // Physics
  22157. if (this._physicsEngine) {
  22158. this.onBeforePhysicsObservable.notifyObservers(this);
  22159. this._physicsEngine._step(defaultFrameTime / 1000);
  22160. this.onAfterPhysicsObservable.notifyObservers(this);
  22161. }
  22162. this.onAfterStepObservable.notifyObservers(this);
  22163. this._currentStepId++;
  22164. stepsTaken++;
  22165. deltaTime -= defaultFrameTime;
  22166. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22167. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22168. }
  22169. else {
  22170. // Animations
  22171. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22172. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22173. this._animate();
  22174. this.onAfterAnimationsObservable.notifyObservers(this);
  22175. // Physics
  22176. if (this._physicsEngine) {
  22177. this.onBeforePhysicsObservable.notifyObservers(this);
  22178. this._physicsEngine._step(deltaTime / 1000.0);
  22179. this.onAfterPhysicsObservable.notifyObservers(this);
  22180. }
  22181. }
  22182. // update gamepad manager
  22183. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22184. this._gamepadManager._checkGamepadsStatus();
  22185. }
  22186. // Before render
  22187. this.onBeforeRenderObservable.notifyObservers(this);
  22188. // Customs render targets
  22189. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22190. var engine = this.getEngine();
  22191. var currentActiveCamera = this.activeCamera;
  22192. if (this.renderTargetsEnabled) {
  22193. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22194. this._intermediateRendering = true;
  22195. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22196. var renderTarget = this.customRenderTargets[customIndex];
  22197. if (renderTarget._shouldRender()) {
  22198. this._renderId++;
  22199. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22200. if (!this.activeCamera)
  22201. throw new Error("Active camera not set");
  22202. // Viewport
  22203. engine.setViewport(this.activeCamera.viewport);
  22204. // Camera
  22205. this.updateTransformMatrix();
  22206. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22207. }
  22208. }
  22209. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22210. this._intermediateRendering = false;
  22211. this._renderId++;
  22212. }
  22213. // Restore back buffer
  22214. if (this.customRenderTargets.length > 0) {
  22215. engine.restoreDefaultFramebuffer();
  22216. }
  22217. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22218. this.activeCamera = currentActiveCamera;
  22219. // Procedural textures
  22220. if (this.proceduralTexturesEnabled) {
  22221. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22222. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22223. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22224. if (proceduralTexture._shouldRender()) {
  22225. proceduralTexture.render();
  22226. }
  22227. }
  22228. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22229. }
  22230. // Clear
  22231. if (this.autoClearDepthAndStencil || this.autoClear) {
  22232. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22233. }
  22234. // Shadows
  22235. if (this.shadowsEnabled) {
  22236. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22237. var light = this.lights[lightIndex];
  22238. var shadowGenerator = light.getShadowGenerator();
  22239. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22240. var shadowMap = (shadowGenerator.getShadowMap());
  22241. if (this.textures.indexOf(shadowMap) !== -1) {
  22242. this._renderTargets.push(shadowMap);
  22243. }
  22244. }
  22245. }
  22246. }
  22247. // Depth renderer
  22248. if (this._depthRenderer) {
  22249. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22250. }
  22251. // Geometry renderer
  22252. if (this._geometryBufferRenderer) {
  22253. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22254. }
  22255. // RenderPipeline
  22256. if (this._postProcessRenderPipelineManager) {
  22257. this._postProcessRenderPipelineManager.update();
  22258. }
  22259. // Multi-cameras?
  22260. if (this.activeCameras.length > 0) {
  22261. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22262. if (cameraIndex > 0) {
  22263. this._engine.clear(null, false, true, true);
  22264. }
  22265. this._processSubCameras(this.activeCameras[cameraIndex]);
  22266. }
  22267. }
  22268. else {
  22269. if (!this.activeCamera) {
  22270. throw new Error("No camera defined");
  22271. }
  22272. this._processSubCameras(this.activeCamera);
  22273. }
  22274. // Intersection checks
  22275. this._checkIntersections();
  22276. // Update the audio listener attached to the camera
  22277. if (BABYLON.AudioEngine) {
  22278. this._updateAudioParameters();
  22279. }
  22280. // After render
  22281. if (this.afterRender) {
  22282. this.afterRender();
  22283. }
  22284. this.onAfterRenderObservable.notifyObservers(this);
  22285. // Cleaning
  22286. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22287. var data = this._toBeDisposed.data[index];
  22288. if (data) {
  22289. data.dispose();
  22290. }
  22291. this._toBeDisposed[index] = null;
  22292. }
  22293. this._toBeDisposed.reset();
  22294. if (this.dumpNextRenderTargets) {
  22295. this.dumpNextRenderTargets = false;
  22296. }
  22297. this._activeBones.addCount(0, true);
  22298. this._activeIndices.addCount(0, true);
  22299. this._activeParticles.addCount(0, true);
  22300. };
  22301. Scene.prototype._updateAudioParameters = function () {
  22302. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22303. return;
  22304. }
  22305. var listeningCamera;
  22306. var audioEngine = BABYLON.Engine.audioEngine;
  22307. if (this.activeCameras.length > 0) {
  22308. listeningCamera = this.activeCameras[0];
  22309. }
  22310. else {
  22311. listeningCamera = this.activeCamera;
  22312. }
  22313. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22314. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22315. // for VR cameras
  22316. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22317. listeningCamera = listeningCamera.rigCameras[0];
  22318. }
  22319. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22320. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22321. cameraDirection.normalize();
  22322. // To avoid some errors on GearVR
  22323. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22324. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22325. }
  22326. var i;
  22327. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22328. var sound = this.mainSoundTrack.soundCollection[i];
  22329. if (sound.useCustomAttenuation) {
  22330. sound.updateDistanceFromListener();
  22331. }
  22332. }
  22333. for (i = 0; i < this.soundTracks.length; i++) {
  22334. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22335. sound = this.soundTracks[i].soundCollection[j];
  22336. if (sound.useCustomAttenuation) {
  22337. sound.updateDistanceFromListener();
  22338. }
  22339. }
  22340. }
  22341. }
  22342. };
  22343. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22344. // Audio
  22345. get: function () {
  22346. return this._audioEnabled;
  22347. },
  22348. set: function (value) {
  22349. this._audioEnabled = value;
  22350. if (BABYLON.AudioEngine) {
  22351. if (this._audioEnabled) {
  22352. this._enableAudio();
  22353. }
  22354. else {
  22355. this._disableAudio();
  22356. }
  22357. }
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Scene.prototype._disableAudio = function () {
  22363. var i;
  22364. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22365. this.mainSoundTrack.soundCollection[i].pause();
  22366. }
  22367. for (i = 0; i < this.soundTracks.length; i++) {
  22368. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22369. this.soundTracks[i].soundCollection[j].pause();
  22370. }
  22371. }
  22372. };
  22373. Scene.prototype._enableAudio = function () {
  22374. var i;
  22375. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22376. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22377. this.mainSoundTrack.soundCollection[i].play();
  22378. }
  22379. }
  22380. for (i = 0; i < this.soundTracks.length; i++) {
  22381. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22382. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22383. this.soundTracks[i].soundCollection[j].play();
  22384. }
  22385. }
  22386. }
  22387. };
  22388. Object.defineProperty(Scene.prototype, "headphone", {
  22389. get: function () {
  22390. return this._headphone;
  22391. },
  22392. set: function (value) {
  22393. this._headphone = value;
  22394. if (BABYLON.AudioEngine) {
  22395. if (this._headphone) {
  22396. this._switchAudioModeForHeadphones();
  22397. }
  22398. else {
  22399. this._switchAudioModeForNormalSpeakers();
  22400. }
  22401. }
  22402. },
  22403. enumerable: true,
  22404. configurable: true
  22405. });
  22406. Scene.prototype._switchAudioModeForHeadphones = function () {
  22407. this.mainSoundTrack.switchPanningModelToHRTF();
  22408. for (var i = 0; i < this.soundTracks.length; i++) {
  22409. this.soundTracks[i].switchPanningModelToHRTF();
  22410. }
  22411. };
  22412. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22413. this.mainSoundTrack.switchPanningModelToEqualPower();
  22414. for (var i = 0; i < this.soundTracks.length; i++) {
  22415. this.soundTracks[i].switchPanningModelToEqualPower();
  22416. }
  22417. };
  22418. Scene.prototype.enableDepthRenderer = function () {
  22419. if (this._depthRenderer) {
  22420. return this._depthRenderer;
  22421. }
  22422. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22423. return this._depthRenderer;
  22424. };
  22425. Scene.prototype.disableDepthRenderer = function () {
  22426. if (!this._depthRenderer) {
  22427. return;
  22428. }
  22429. this._depthRenderer.dispose();
  22430. this._depthRenderer = null;
  22431. };
  22432. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22433. if (ratio === void 0) { ratio = 1; }
  22434. if (this._geometryBufferRenderer) {
  22435. return this._geometryBufferRenderer;
  22436. }
  22437. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22438. if (!this._geometryBufferRenderer.isSupported) {
  22439. this._geometryBufferRenderer = null;
  22440. }
  22441. return this._geometryBufferRenderer;
  22442. };
  22443. Scene.prototype.disableGeometryBufferRenderer = function () {
  22444. if (!this._geometryBufferRenderer) {
  22445. return;
  22446. }
  22447. this._geometryBufferRenderer.dispose();
  22448. this._geometryBufferRenderer = null;
  22449. };
  22450. Scene.prototype.freezeMaterials = function () {
  22451. for (var i = 0; i < this.materials.length; i++) {
  22452. this.materials[i].freeze();
  22453. }
  22454. };
  22455. Scene.prototype.unfreezeMaterials = function () {
  22456. for (var i = 0; i < this.materials.length; i++) {
  22457. this.materials[i].unfreeze();
  22458. }
  22459. };
  22460. Scene.prototype.dispose = function () {
  22461. this.beforeRender = null;
  22462. this.afterRender = null;
  22463. this.skeletons = [];
  22464. this.morphTargetManagers = [];
  22465. this.importedMeshesFiles = new Array();
  22466. this.stopAllAnimations();
  22467. this.resetCachedMaterial();
  22468. if (this._depthRenderer) {
  22469. this._depthRenderer.dispose();
  22470. }
  22471. if (this._gamepadManager) {
  22472. this._gamepadManager.dispose();
  22473. this._gamepadManager = null;
  22474. }
  22475. // Smart arrays
  22476. if (this.activeCamera) {
  22477. this.activeCamera._activeMeshes.dispose();
  22478. this.activeCamera = null;
  22479. }
  22480. this._activeMeshes.dispose();
  22481. this._renderingManager.dispose();
  22482. this._processedMaterials.dispose();
  22483. this._activeParticleSystems.dispose();
  22484. this._activeSkeletons.dispose();
  22485. this._softwareSkinnedMeshes.dispose();
  22486. this._renderTargets.dispose();
  22487. if (this._boundingBoxRenderer) {
  22488. this._boundingBoxRenderer.dispose();
  22489. }
  22490. this._meshesForIntersections.dispose();
  22491. this._toBeDisposed.dispose();
  22492. // Abort active requests
  22493. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22494. var request = _a[_i];
  22495. request.abort();
  22496. }
  22497. // Debug layer
  22498. if (this._debugLayer) {
  22499. this._debugLayer.hide();
  22500. }
  22501. // Events
  22502. this.onDisposeObservable.notifyObservers(this);
  22503. this.onDisposeObservable.clear();
  22504. this.onBeforeRenderObservable.clear();
  22505. this.onAfterRenderObservable.clear();
  22506. this.OnBeforeRenderTargetsRenderObservable.clear();
  22507. this.OnAfterRenderTargetsRenderObservable.clear();
  22508. this.onAfterStepObservable.clear();
  22509. this.onBeforeStepObservable.clear();
  22510. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22511. this.onAfterActiveMeshesEvaluationObservable.clear();
  22512. this.onBeforeParticlesRenderingObservable.clear();
  22513. this.onAfterParticlesRenderingObservable.clear();
  22514. this.onBeforeSpritesRenderingObservable.clear();
  22515. this.onAfterSpritesRenderingObservable.clear();
  22516. this.onBeforeDrawPhaseObservable.clear();
  22517. this.onAfterDrawPhaseObservable.clear();
  22518. this.onBeforePhysicsObservable.clear();
  22519. this.onAfterPhysicsObservable.clear();
  22520. this.onBeforeAnimationsObservable.clear();
  22521. this.onAfterAnimationsObservable.clear();
  22522. this.onDataLoadedObservable.clear();
  22523. this.detachControl();
  22524. // Release sounds & sounds tracks
  22525. if (BABYLON.AudioEngine) {
  22526. this.disposeSounds();
  22527. }
  22528. // VR Helper
  22529. if (this.VRHelper) {
  22530. this.VRHelper.dispose();
  22531. }
  22532. // Detach cameras
  22533. var canvas = this._engine.getRenderingCanvas();
  22534. if (canvas) {
  22535. var index;
  22536. for (index = 0; index < this.cameras.length; index++) {
  22537. this.cameras[index].detachControl(canvas);
  22538. }
  22539. }
  22540. // Release animation groups
  22541. while (this.animationGroups.length) {
  22542. this.animationGroups[0].dispose();
  22543. }
  22544. // Release lights
  22545. while (this.lights.length) {
  22546. this.lights[0].dispose();
  22547. }
  22548. // Release meshes
  22549. while (this.meshes.length) {
  22550. this.meshes[0].dispose(true);
  22551. }
  22552. while (this.transformNodes.length) {
  22553. this.removeTransformNode(this.transformNodes[0]);
  22554. }
  22555. // Release cameras
  22556. while (this.cameras.length) {
  22557. this.cameras[0].dispose();
  22558. }
  22559. // Release materials
  22560. if (this.defaultMaterial) {
  22561. this.defaultMaterial.dispose();
  22562. }
  22563. while (this.multiMaterials.length) {
  22564. this.multiMaterials[0].dispose();
  22565. }
  22566. while (this.materials.length) {
  22567. this.materials[0].dispose();
  22568. }
  22569. // Release particles
  22570. while (this.particleSystems.length) {
  22571. this.particleSystems[0].dispose();
  22572. }
  22573. // Release sprites
  22574. while (this.spriteManagers.length) {
  22575. this.spriteManagers[0].dispose();
  22576. }
  22577. // Release postProcesses
  22578. while (this.postProcesses.length) {
  22579. this.postProcesses[0].dispose();
  22580. }
  22581. // Release layers
  22582. while (this.layers.length) {
  22583. this.layers[0].dispose();
  22584. }
  22585. while (this.highlightLayers.length) {
  22586. this.highlightLayers[0].dispose();
  22587. }
  22588. // Release textures
  22589. while (this.textures.length) {
  22590. this.textures[0].dispose();
  22591. }
  22592. // Release UBO
  22593. this._sceneUbo.dispose();
  22594. if (this._alternateSceneUbo) {
  22595. this._alternateSceneUbo.dispose();
  22596. }
  22597. // Post-processes
  22598. this.postProcessManager.dispose();
  22599. if (this._postProcessRenderPipelineManager) {
  22600. this._postProcessRenderPipelineManager.dispose();
  22601. }
  22602. // Physics
  22603. if (this._physicsEngine) {
  22604. this.disablePhysicsEngine();
  22605. }
  22606. // Remove from engine
  22607. index = this._engine.scenes.indexOf(this);
  22608. if (index > -1) {
  22609. this._engine.scenes.splice(index, 1);
  22610. }
  22611. this._engine.wipeCaches(true);
  22612. this._isDisposed = true;
  22613. };
  22614. Object.defineProperty(Scene.prototype, "isDisposed", {
  22615. get: function () {
  22616. return this._isDisposed;
  22617. },
  22618. enumerable: true,
  22619. configurable: true
  22620. });
  22621. // Release sounds & sounds tracks
  22622. Scene.prototype.disposeSounds = function () {
  22623. if (!this._mainSoundTrack) {
  22624. return;
  22625. }
  22626. this.mainSoundTrack.dispose();
  22627. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22628. this.soundTracks[scIndex].dispose();
  22629. }
  22630. };
  22631. // Octrees
  22632. Scene.prototype.getWorldExtends = function () {
  22633. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22634. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22635. for (var index = 0; index < this.meshes.length; index++) {
  22636. var mesh = this.meshes[index];
  22637. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22638. continue;
  22639. }
  22640. mesh.computeWorldMatrix(true);
  22641. var boundingInfo = mesh.getBoundingInfo();
  22642. var minBox = boundingInfo.boundingBox.minimumWorld;
  22643. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22644. BABYLON.Tools.CheckExtends(minBox, min, max);
  22645. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22646. }
  22647. return {
  22648. min: min,
  22649. max: max
  22650. };
  22651. };
  22652. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22653. if (maxCapacity === void 0) { maxCapacity = 64; }
  22654. if (maxDepth === void 0) { maxDepth = 2; }
  22655. if (!this._selectionOctree) {
  22656. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22657. }
  22658. var worldExtends = this.getWorldExtends();
  22659. // Update octree
  22660. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22661. return this._selectionOctree;
  22662. };
  22663. // Picking
  22664. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22665. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22666. var result = BABYLON.Ray.Zero();
  22667. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22668. return result;
  22669. };
  22670. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22671. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22672. var engine = this._engine;
  22673. if (!camera) {
  22674. if (!this.activeCamera)
  22675. throw new Error("Active camera not set");
  22676. camera = this.activeCamera;
  22677. }
  22678. var cameraViewport = camera.viewport;
  22679. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22680. // Moving coordinates to local viewport world
  22681. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22682. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22683. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22684. return this;
  22685. };
  22686. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22687. var result = BABYLON.Ray.Zero();
  22688. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22689. return result;
  22690. };
  22691. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22692. if (!BABYLON.PickingInfo) {
  22693. return this;
  22694. }
  22695. var engine = this._engine;
  22696. if (!camera) {
  22697. if (!this.activeCamera)
  22698. throw new Error("Active camera not set");
  22699. camera = this.activeCamera;
  22700. }
  22701. var cameraViewport = camera.viewport;
  22702. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22703. var identity = BABYLON.Matrix.Identity();
  22704. // Moving coordinates to local viewport world
  22705. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22706. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22707. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22708. return this;
  22709. };
  22710. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22711. if (!BABYLON.PickingInfo) {
  22712. return null;
  22713. }
  22714. var pickingInfo = null;
  22715. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22716. var mesh = this.meshes[meshIndex];
  22717. if (predicate) {
  22718. if (!predicate(mesh)) {
  22719. continue;
  22720. }
  22721. }
  22722. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22723. continue;
  22724. }
  22725. var world = mesh.getWorldMatrix();
  22726. var ray = rayFunction(world);
  22727. var result = mesh.intersects(ray, fastCheck);
  22728. if (!result || !result.hit)
  22729. continue;
  22730. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22731. continue;
  22732. pickingInfo = result;
  22733. if (fastCheck) {
  22734. break;
  22735. }
  22736. }
  22737. return pickingInfo || new BABYLON.PickingInfo();
  22738. };
  22739. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22740. if (!BABYLON.PickingInfo) {
  22741. return null;
  22742. }
  22743. var pickingInfos = new Array();
  22744. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22745. var mesh = this.meshes[meshIndex];
  22746. if (predicate) {
  22747. if (!predicate(mesh)) {
  22748. continue;
  22749. }
  22750. }
  22751. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22752. continue;
  22753. }
  22754. var world = mesh.getWorldMatrix();
  22755. var ray = rayFunction(world);
  22756. var result = mesh.intersects(ray, false);
  22757. if (!result || !result.hit)
  22758. continue;
  22759. pickingInfos.push(result);
  22760. }
  22761. return pickingInfos;
  22762. };
  22763. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22764. if (!BABYLON.PickingInfo) {
  22765. return null;
  22766. }
  22767. var pickingInfo = null;
  22768. if (!camera) {
  22769. if (!this.activeCamera) {
  22770. return null;
  22771. }
  22772. camera = this.activeCamera;
  22773. }
  22774. if (this.spriteManagers.length > 0) {
  22775. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22776. var spriteManager = this.spriteManagers[spriteIndex];
  22777. if (!spriteManager.isPickable) {
  22778. continue;
  22779. }
  22780. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22781. if (!result || !result.hit)
  22782. continue;
  22783. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22784. continue;
  22785. pickingInfo = result;
  22786. if (fastCheck) {
  22787. break;
  22788. }
  22789. }
  22790. }
  22791. return pickingInfo || new BABYLON.PickingInfo();
  22792. };
  22793. /** Launch a ray to try to pick a mesh in the scene
  22794. * @param x position on screen
  22795. * @param y position on screen
  22796. * @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
  22797. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22798. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22799. */
  22800. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22801. var _this = this;
  22802. if (!BABYLON.PickingInfo) {
  22803. return null;
  22804. }
  22805. return this._internalPick(function (world) {
  22806. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22807. return _this._tempPickingRay;
  22808. }, predicate, fastCheck);
  22809. };
  22810. /** Launch a ray to try to pick a sprite in the scene
  22811. * @param x position on screen
  22812. * @param y position on screen
  22813. * @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
  22814. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22815. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22816. */
  22817. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22818. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22819. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22820. };
  22821. /** Use the given ray to pick a mesh in the scene
  22822. * @param ray The ray to use to pick meshes
  22823. * @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
  22824. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22825. */
  22826. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22827. var _this = this;
  22828. return this._internalPick(function (world) {
  22829. if (!_this._pickWithRayInverseMatrix) {
  22830. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22831. }
  22832. world.invertToRef(_this._pickWithRayInverseMatrix);
  22833. if (!_this._cachedRayForTransform) {
  22834. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22835. }
  22836. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22837. return _this._cachedRayForTransform;
  22838. }, predicate, fastCheck);
  22839. };
  22840. /**
  22841. * Launch a ray to try to pick a mesh in the scene
  22842. * @param x X position on screen
  22843. * @param y Y position on screen
  22844. * @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
  22845. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22846. */
  22847. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22848. var _this = this;
  22849. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22850. };
  22851. /**
  22852. * Launch a ray to try to pick a mesh in the scene
  22853. * @param ray Ray to use
  22854. * @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
  22855. */
  22856. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22857. var _this = this;
  22858. return this._internalMultiPick(function (world) {
  22859. if (!_this._pickWithRayInverseMatrix) {
  22860. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22861. }
  22862. world.invertToRef(_this._pickWithRayInverseMatrix);
  22863. if (!_this._cachedRayForTransform) {
  22864. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22865. }
  22866. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22867. return _this._cachedRayForTransform;
  22868. }, predicate);
  22869. };
  22870. Scene.prototype.setPointerOverMesh = function (mesh) {
  22871. if (this._pointerOverMesh === mesh) {
  22872. return;
  22873. }
  22874. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22875. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22876. }
  22877. this._pointerOverMesh = mesh;
  22878. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22879. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22880. }
  22881. };
  22882. Scene.prototype.getPointerOverMesh = function () {
  22883. return this._pointerOverMesh;
  22884. };
  22885. Scene.prototype.setPointerOverSprite = function (sprite) {
  22886. if (this._pointerOverSprite === sprite) {
  22887. return;
  22888. }
  22889. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22890. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22891. }
  22892. this._pointerOverSprite = sprite;
  22893. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22894. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22895. }
  22896. };
  22897. Scene.prototype.getPointerOverSprite = function () {
  22898. return this._pointerOverSprite;
  22899. };
  22900. // Physics
  22901. Scene.prototype.getPhysicsEngine = function () {
  22902. return this._physicsEngine;
  22903. };
  22904. /**
  22905. * Enables physics to the current scene
  22906. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22907. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22908. * @return {boolean} was the physics engine initialized
  22909. */
  22910. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22911. if (gravity === void 0) { gravity = null; }
  22912. if (this._physicsEngine) {
  22913. return true;
  22914. }
  22915. try {
  22916. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22917. return true;
  22918. }
  22919. catch (e) {
  22920. BABYLON.Tools.Error(e.message);
  22921. return false;
  22922. }
  22923. };
  22924. Scene.prototype.disablePhysicsEngine = function () {
  22925. if (!this._physicsEngine) {
  22926. return;
  22927. }
  22928. this._physicsEngine.dispose();
  22929. this._physicsEngine = null;
  22930. };
  22931. Scene.prototype.isPhysicsEnabled = function () {
  22932. return this._physicsEngine !== undefined;
  22933. };
  22934. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22935. var mesh = compound.parts[0].mesh;
  22936. if (mesh.physicsImpostor) {
  22937. mesh.physicsImpostor.dispose();
  22938. mesh.physicsImpostor = null;
  22939. }
  22940. };
  22941. // Misc.
  22942. Scene.prototype._rebuildGeometries = function () {
  22943. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22944. var geometry = _a[_i];
  22945. geometry._rebuild();
  22946. }
  22947. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22948. var mesh = _c[_b];
  22949. mesh._rebuild();
  22950. }
  22951. if (this.postProcessManager) {
  22952. this.postProcessManager._rebuild();
  22953. }
  22954. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22955. var layer = _e[_d];
  22956. layer._rebuild();
  22957. }
  22958. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22959. var highlightLayer = _g[_f];
  22960. highlightLayer._rebuild();
  22961. }
  22962. if (this._boundingBoxRenderer) {
  22963. this._boundingBoxRenderer._rebuild();
  22964. }
  22965. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22966. var system = _j[_h];
  22967. system.rebuild();
  22968. }
  22969. if (this._postProcessRenderPipelineManager) {
  22970. this._postProcessRenderPipelineManager._rebuild();
  22971. }
  22972. };
  22973. Scene.prototype._rebuildTextures = function () {
  22974. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22975. var texture = _a[_i];
  22976. texture._rebuild();
  22977. }
  22978. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22979. };
  22980. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22981. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22982. if (replace === void 0) { replace = false; }
  22983. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22984. // Dispose existing camera or light in replace mode.
  22985. if (replace) {
  22986. if (this.activeCamera) {
  22987. this.activeCamera.dispose();
  22988. this.activeCamera = null;
  22989. }
  22990. if (this.lights) {
  22991. for (var i = 0; i < this.lights.length; i++) {
  22992. this.lights[i].dispose();
  22993. }
  22994. }
  22995. }
  22996. // Light
  22997. if (this.lights.length === 0) {
  22998. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22999. }
  23000. // Camera
  23001. if (!this.activeCamera) {
  23002. var worldExtends = this.getWorldExtends();
  23003. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23004. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23005. var camera;
  23006. var radius = worldSize.length() * 1.5;
  23007. if (createArcRotateCamera) {
  23008. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23009. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23010. arcRotateCamera.wheelPrecision = 100 / radius;
  23011. camera = arcRotateCamera;
  23012. }
  23013. else {
  23014. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23015. freeCamera.setTarget(worldCenter);
  23016. camera = freeCamera;
  23017. }
  23018. camera.minZ = radius * 0.01;
  23019. camera.maxZ = radius * 1000;
  23020. camera.speed = radius * 0.2;
  23021. this.activeCamera = camera;
  23022. var canvas = this.getEngine().getRenderingCanvas();
  23023. if (attachCameraControls && canvas) {
  23024. camera.attachControl(canvas);
  23025. }
  23026. }
  23027. };
  23028. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23029. if (pbr === void 0) { pbr = false; }
  23030. if (scale === void 0) { scale = 1000; }
  23031. if (blur === void 0) { blur = 0; }
  23032. if (environmentTexture) {
  23033. this.environmentTexture = environmentTexture;
  23034. }
  23035. if (!this.environmentTexture) {
  23036. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23037. return null;
  23038. }
  23039. // Skybox
  23040. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23041. if (pbr) {
  23042. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23043. hdrSkyboxMaterial.backFaceCulling = false;
  23044. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23045. if (hdrSkyboxMaterial.reflectionTexture) {
  23046. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23047. }
  23048. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23049. hdrSkyboxMaterial.disableLighting = true;
  23050. hdrSkyboxMaterial.twoSidedLighting = true;
  23051. hdrSkybox.infiniteDistance = true;
  23052. hdrSkybox.material = hdrSkyboxMaterial;
  23053. }
  23054. else {
  23055. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23056. skyboxMaterial.backFaceCulling = false;
  23057. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23058. if (skyboxMaterial.reflectionTexture) {
  23059. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23060. }
  23061. skyboxMaterial.disableLighting = true;
  23062. hdrSkybox.infiniteDistance = true;
  23063. hdrSkybox.material = skyboxMaterial;
  23064. }
  23065. return hdrSkybox;
  23066. };
  23067. Scene.prototype.createDefaultEnvironment = function (options) {
  23068. if (BABYLON.EnvironmentHelper) {
  23069. return new BABYLON.EnvironmentHelper(options, this);
  23070. }
  23071. return null;
  23072. };
  23073. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23074. if (webVROptions === void 0) { webVROptions = {}; }
  23075. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23076. };
  23077. // Tags
  23078. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23079. if (tagsQuery === undefined) {
  23080. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23081. return list;
  23082. }
  23083. var listByTags = [];
  23084. forEach = forEach || (function (item) { return; });
  23085. for (var i in list) {
  23086. var item = list[i];
  23087. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23088. listByTags.push(item);
  23089. forEach(item);
  23090. }
  23091. }
  23092. return listByTags;
  23093. };
  23094. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23095. return this._getByTags(this.meshes, tagsQuery, forEach);
  23096. };
  23097. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23098. return this._getByTags(this.cameras, tagsQuery, forEach);
  23099. };
  23100. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23101. return this._getByTags(this.lights, tagsQuery, forEach);
  23102. };
  23103. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23104. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23105. };
  23106. /**
  23107. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23108. * This allowed control for front to back rendering or reversly depending of the special needs.
  23109. *
  23110. * @param renderingGroupId The rendering group id corresponding to its index
  23111. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23112. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23113. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23114. */
  23115. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23116. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23117. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23118. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23119. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23120. };
  23121. /**
  23122. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23123. *
  23124. * @param renderingGroupId The rendering group id corresponding to its index
  23125. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23126. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23127. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23128. */
  23129. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23130. if (depth === void 0) { depth = true; }
  23131. if (stencil === void 0) { stencil = true; }
  23132. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23133. };
  23134. /**
  23135. * Will flag all materials as dirty to trigger new shader compilation
  23136. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23137. */
  23138. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23139. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23140. var material = _a[_i];
  23141. if (predicate && !predicate(material)) {
  23142. continue;
  23143. }
  23144. material.markAsDirty(flag);
  23145. }
  23146. };
  23147. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23148. var _this = this;
  23149. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23150. this._activeRequests.push(request);
  23151. request.onCompleteObservable.add(function (request) {
  23152. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23153. });
  23154. return request;
  23155. };
  23156. // Statics
  23157. Scene._FOGMODE_NONE = 0;
  23158. Scene._FOGMODE_EXP = 1;
  23159. Scene._FOGMODE_EXP2 = 2;
  23160. Scene._FOGMODE_LINEAR = 3;
  23161. Scene._uniqueIdCounter = 0;
  23162. Scene.MinDeltaTime = 1.0;
  23163. Scene.MaxDeltaTime = 1000.0;
  23164. /** The distance in pixel that you have to move to prevent some events */
  23165. Scene.DragMovementThreshold = 10; // in pixels
  23166. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23167. Scene.LongPressDelay = 500; // in milliseconds
  23168. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23169. Scene.DoubleClickDelay = 300; // in milliseconds
  23170. /** If you need to check double click without raising a single click at first click, enable this flag */
  23171. Scene.ExclusiveDoubleClickMode = false;
  23172. return Scene;
  23173. }());
  23174. BABYLON.Scene = Scene;
  23175. })(BABYLON || (BABYLON = {}));
  23176. //# sourceMappingURL=babylon.scene.js.map
  23177. var BABYLON;
  23178. (function (BABYLON) {
  23179. var AssetContainer = /** @class */ (function () {
  23180. function AssetContainer(scene) {
  23181. // Objects
  23182. this.cameras = new Array();
  23183. this.lights = new Array();
  23184. this.meshes = new Array();
  23185. this.skeletons = new Array();
  23186. this.particleSystems = new Array();
  23187. this.animations = new Array();
  23188. this.multiMaterials = new Array();
  23189. this.materials = new Array();
  23190. this.morphTargetManagers = new Array();
  23191. this.geometries = new Array();
  23192. this.transformNodes = new Array();
  23193. this.lensFlareSystems = new Array();
  23194. this.shadowGenerators = new Array();
  23195. this.actionManagers = new Array();
  23196. this.sounds = new Array();
  23197. this.scene = scene;
  23198. }
  23199. AssetContainer.prototype.addAllToScene = function () {
  23200. var _this = this;
  23201. this.cameras.forEach(function (o) {
  23202. _this.scene.addCamera(o);
  23203. });
  23204. this.lights.forEach(function (o) {
  23205. _this.scene.addLight(o);
  23206. });
  23207. this.meshes.forEach(function (o) {
  23208. _this.scene.addMesh(o);
  23209. });
  23210. this.skeletons.forEach(function (o) {
  23211. _this.scene.addSkeleton(o);
  23212. });
  23213. this.particleSystems.forEach(function (o) {
  23214. _this.scene.addParticleSystem(o);
  23215. });
  23216. this.animations.forEach(function (o) {
  23217. _this.scene.addAnimation(o);
  23218. });
  23219. this.multiMaterials.forEach(function (o) {
  23220. _this.scene.addMultiMaterial(o);
  23221. });
  23222. this.materials.forEach(function (o) {
  23223. _this.scene.addMaterial(o);
  23224. });
  23225. this.morphTargetManagers.forEach(function (o) {
  23226. _this.scene.addMorphTargetManager(o);
  23227. });
  23228. this.geometries.forEach(function (o) {
  23229. _this.scene.addGeometry(o);
  23230. });
  23231. this.transformNodes.forEach(function (o) {
  23232. _this.scene.addTransformNode(o);
  23233. });
  23234. this.lensFlareSystems.forEach(function (o) {
  23235. _this.scene.addLensFlareSystem(o);
  23236. });
  23237. this.actionManagers.forEach(function (o) {
  23238. _this.scene.addActionManager(o);
  23239. });
  23240. this.sounds.forEach(function (o) {
  23241. o.play();
  23242. o.autoplay = true;
  23243. _this.scene.mainSoundTrack.AddSound(o);
  23244. });
  23245. };
  23246. AssetContainer.prototype.removeAllFromScene = function () {
  23247. var _this = this;
  23248. this.cameras.forEach(function (o) {
  23249. _this.scene.removeCamera(o);
  23250. });
  23251. this.lights.forEach(function (o) {
  23252. _this.scene.removeLight(o);
  23253. });
  23254. this.meshes.forEach(function (o) {
  23255. _this.scene.removeMesh(o);
  23256. });
  23257. this.skeletons.forEach(function (o) {
  23258. _this.scene.removeSkeleton(o);
  23259. });
  23260. this.particleSystems.forEach(function (o) {
  23261. _this.scene.removeParticleSystem(o);
  23262. });
  23263. this.animations.forEach(function (o) {
  23264. _this.scene.removeAnimation(o);
  23265. });
  23266. this.multiMaterials.forEach(function (o) {
  23267. _this.scene.removeMultiMaterial(o);
  23268. });
  23269. this.materials.forEach(function (o) {
  23270. _this.scene.removeMaterial(o);
  23271. });
  23272. this.morphTargetManagers.forEach(function (o) {
  23273. _this.scene.removeMorphTargetManager(o);
  23274. });
  23275. this.geometries.forEach(function (o) {
  23276. _this.scene.removeGeometry(o);
  23277. });
  23278. this.transformNodes.forEach(function (o) {
  23279. _this.scene.removeTransformNode(o);
  23280. });
  23281. this.lensFlareSystems.forEach(function (o) {
  23282. _this.scene.removeLensFlareSystem(o);
  23283. });
  23284. this.actionManagers.forEach(function (o) {
  23285. _this.scene.removeActionManager(o);
  23286. });
  23287. this.sounds.forEach(function (o) {
  23288. o.stop();
  23289. o.autoplay = false;
  23290. _this.scene.mainSoundTrack.RemoveSound(o);
  23291. });
  23292. };
  23293. return AssetContainer;
  23294. }());
  23295. BABYLON.AssetContainer = AssetContainer;
  23296. })(BABYLON || (BABYLON = {}));
  23297. //# sourceMappingURL=babylon.assetContainer.js.map
  23298. var BABYLON;
  23299. (function (BABYLON) {
  23300. var Buffer = /** @class */ (function () {
  23301. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23302. if (instanced === void 0) { instanced = false; }
  23303. if (engine instanceof BABYLON.Mesh) {
  23304. this._engine = engine.getScene().getEngine();
  23305. }
  23306. else {
  23307. this._engine = engine;
  23308. }
  23309. this._updatable = updatable;
  23310. this._data = data;
  23311. this._strideSize = stride;
  23312. if (!postponeInternalCreation) {
  23313. this.create();
  23314. }
  23315. this._instanced = instanced;
  23316. this._instanceDivisor = instanced ? 1 : 0;
  23317. }
  23318. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23319. // a lot of these parameters are ignored as they are overriden by the buffer
  23320. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23321. };
  23322. // Properties
  23323. Buffer.prototype.isUpdatable = function () {
  23324. return this._updatable;
  23325. };
  23326. Buffer.prototype.getData = function () {
  23327. return this._data;
  23328. };
  23329. Buffer.prototype.getBuffer = function () {
  23330. return this._buffer;
  23331. };
  23332. Buffer.prototype.getStrideSize = function () {
  23333. return this._strideSize;
  23334. };
  23335. Buffer.prototype.getIsInstanced = function () {
  23336. return this._instanced;
  23337. };
  23338. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23339. get: function () {
  23340. return this._instanceDivisor;
  23341. },
  23342. set: function (value) {
  23343. this._instanceDivisor = value;
  23344. if (value == 0) {
  23345. this._instanced = false;
  23346. }
  23347. else {
  23348. this._instanced = true;
  23349. }
  23350. },
  23351. enumerable: true,
  23352. configurable: true
  23353. });
  23354. // Methods
  23355. Buffer.prototype.create = function (data) {
  23356. if (data === void 0) { data = null; }
  23357. if (!data && this._buffer) {
  23358. return; // nothing to do
  23359. }
  23360. data = data || this._data;
  23361. if (!data) {
  23362. return;
  23363. }
  23364. if (!this._buffer) {
  23365. if (this._updatable) {
  23366. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23367. this._data = data;
  23368. }
  23369. else {
  23370. this._buffer = this._engine.createVertexBuffer(data);
  23371. }
  23372. }
  23373. else if (this._updatable) {
  23374. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23375. this._data = data;
  23376. }
  23377. };
  23378. Buffer.prototype._rebuild = function () {
  23379. this._buffer = null;
  23380. this.create(this._data);
  23381. };
  23382. Buffer.prototype.update = function (data) {
  23383. this.create(data);
  23384. };
  23385. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23386. if (!this._buffer) {
  23387. return;
  23388. }
  23389. if (this._updatable) {
  23390. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23391. this._data = null;
  23392. }
  23393. };
  23394. Buffer.prototype.dispose = function () {
  23395. if (!this._buffer) {
  23396. return;
  23397. }
  23398. if (this._engine._releaseBuffer(this._buffer)) {
  23399. this._buffer = null;
  23400. }
  23401. };
  23402. return Buffer;
  23403. }());
  23404. BABYLON.Buffer = Buffer;
  23405. })(BABYLON || (BABYLON = {}));
  23406. //# sourceMappingURL=babylon.buffer.js.map
  23407. var BABYLON;
  23408. (function (BABYLON) {
  23409. var VertexBuffer = /** @class */ (function () {
  23410. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23411. if (!stride) {
  23412. // Deduce stride from kind
  23413. switch (kind) {
  23414. case VertexBuffer.PositionKind:
  23415. stride = 3;
  23416. break;
  23417. case VertexBuffer.NormalKind:
  23418. stride = 3;
  23419. break;
  23420. case VertexBuffer.UVKind:
  23421. case VertexBuffer.UV2Kind:
  23422. case VertexBuffer.UV3Kind:
  23423. case VertexBuffer.UV4Kind:
  23424. case VertexBuffer.UV5Kind:
  23425. case VertexBuffer.UV6Kind:
  23426. stride = 2;
  23427. break;
  23428. case VertexBuffer.TangentKind:
  23429. case VertexBuffer.ColorKind:
  23430. stride = 4;
  23431. break;
  23432. case VertexBuffer.MatricesIndicesKind:
  23433. case VertexBuffer.MatricesIndicesExtraKind:
  23434. stride = 4;
  23435. break;
  23436. case VertexBuffer.MatricesWeightsKind:
  23437. case VertexBuffer.MatricesWeightsExtraKind:
  23438. default:
  23439. stride = 4;
  23440. break;
  23441. }
  23442. }
  23443. if (data instanceof BABYLON.Buffer) {
  23444. if (!stride) {
  23445. stride = data.getStrideSize();
  23446. }
  23447. this._buffer = data;
  23448. this._ownsBuffer = false;
  23449. }
  23450. else {
  23451. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23452. this._ownsBuffer = true;
  23453. }
  23454. this._stride = stride;
  23455. this._offset = offset ? offset : 0;
  23456. this._size = size ? size : stride;
  23457. this._kind = kind;
  23458. }
  23459. VertexBuffer.prototype._rebuild = function () {
  23460. if (!this._buffer) {
  23461. return;
  23462. }
  23463. this._buffer._rebuild();
  23464. };
  23465. /**
  23466. * Returns the kind of the VertexBuffer (string).
  23467. */
  23468. VertexBuffer.prototype.getKind = function () {
  23469. return this._kind;
  23470. };
  23471. // Properties
  23472. /**
  23473. * Boolean : is the VertexBuffer updatable ?
  23474. */
  23475. VertexBuffer.prototype.isUpdatable = function () {
  23476. return this._buffer.isUpdatable();
  23477. };
  23478. /**
  23479. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23480. */
  23481. VertexBuffer.prototype.getData = function () {
  23482. return this._buffer.getData();
  23483. };
  23484. /**
  23485. * Returns the WebGLBuffer associated to the VertexBuffer.
  23486. */
  23487. VertexBuffer.prototype.getBuffer = function () {
  23488. return this._buffer.getBuffer();
  23489. };
  23490. /**
  23491. * Returns the stride of the VertexBuffer (integer).
  23492. */
  23493. VertexBuffer.prototype.getStrideSize = function () {
  23494. return this._stride;
  23495. };
  23496. /**
  23497. * Returns the offset (integer).
  23498. */
  23499. VertexBuffer.prototype.getOffset = function () {
  23500. return this._offset;
  23501. };
  23502. /**
  23503. * Returns the VertexBuffer total size (integer).
  23504. */
  23505. VertexBuffer.prototype.getSize = function () {
  23506. return this._size;
  23507. };
  23508. /**
  23509. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23510. */
  23511. VertexBuffer.prototype.getIsInstanced = function () {
  23512. return this._buffer.getIsInstanced();
  23513. };
  23514. /**
  23515. * Returns the instancing divisor, zero for non-instanced (integer).
  23516. */
  23517. VertexBuffer.prototype.getInstanceDivisor = function () {
  23518. return this._buffer.instanceDivisor;
  23519. };
  23520. // Methods
  23521. /**
  23522. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23523. * Returns the created WebGLBuffer.
  23524. */
  23525. VertexBuffer.prototype.create = function (data) {
  23526. return this._buffer.create(data);
  23527. };
  23528. /**
  23529. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23530. * Returns the updated WebGLBuffer.
  23531. */
  23532. VertexBuffer.prototype.update = function (data) {
  23533. return this._buffer.update(data);
  23534. };
  23535. /**
  23536. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23537. * Returns the directly updated WebGLBuffer.
  23538. */
  23539. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23540. return this._buffer.updateDirectly(data, offset);
  23541. };
  23542. /**
  23543. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23544. */
  23545. VertexBuffer.prototype.dispose = function () {
  23546. if (this._ownsBuffer) {
  23547. this._buffer.dispose();
  23548. }
  23549. };
  23550. Object.defineProperty(VertexBuffer, "PositionKind", {
  23551. get: function () {
  23552. return VertexBuffer._PositionKind;
  23553. },
  23554. enumerable: true,
  23555. configurable: true
  23556. });
  23557. Object.defineProperty(VertexBuffer, "NormalKind", {
  23558. get: function () {
  23559. return VertexBuffer._NormalKind;
  23560. },
  23561. enumerable: true,
  23562. configurable: true
  23563. });
  23564. Object.defineProperty(VertexBuffer, "TangentKind", {
  23565. get: function () {
  23566. return VertexBuffer._TangentKind;
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. Object.defineProperty(VertexBuffer, "UVKind", {
  23572. get: function () {
  23573. return VertexBuffer._UVKind;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23579. get: function () {
  23580. return VertexBuffer._UV2Kind;
  23581. },
  23582. enumerable: true,
  23583. configurable: true
  23584. });
  23585. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23586. get: function () {
  23587. return VertexBuffer._UV3Kind;
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23593. get: function () {
  23594. return VertexBuffer._UV4Kind;
  23595. },
  23596. enumerable: true,
  23597. configurable: true
  23598. });
  23599. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23600. get: function () {
  23601. return VertexBuffer._UV5Kind;
  23602. },
  23603. enumerable: true,
  23604. configurable: true
  23605. });
  23606. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23607. get: function () {
  23608. return VertexBuffer._UV6Kind;
  23609. },
  23610. enumerable: true,
  23611. configurable: true
  23612. });
  23613. Object.defineProperty(VertexBuffer, "ColorKind", {
  23614. get: function () {
  23615. return VertexBuffer._ColorKind;
  23616. },
  23617. enumerable: true,
  23618. configurable: true
  23619. });
  23620. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23621. get: function () {
  23622. return VertexBuffer._MatricesIndicesKind;
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23628. get: function () {
  23629. return VertexBuffer._MatricesWeightsKind;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23635. get: function () {
  23636. return VertexBuffer._MatricesIndicesExtraKind;
  23637. },
  23638. enumerable: true,
  23639. configurable: true
  23640. });
  23641. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23642. get: function () {
  23643. return VertexBuffer._MatricesWeightsExtraKind;
  23644. },
  23645. enumerable: true,
  23646. configurable: true
  23647. });
  23648. // Enums
  23649. VertexBuffer._PositionKind = "position";
  23650. VertexBuffer._NormalKind = "normal";
  23651. VertexBuffer._TangentKind = "tangent";
  23652. VertexBuffer._UVKind = "uv";
  23653. VertexBuffer._UV2Kind = "uv2";
  23654. VertexBuffer._UV3Kind = "uv3";
  23655. VertexBuffer._UV4Kind = "uv4";
  23656. VertexBuffer._UV5Kind = "uv5";
  23657. VertexBuffer._UV6Kind = "uv6";
  23658. VertexBuffer._ColorKind = "color";
  23659. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23660. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23661. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23662. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23663. return VertexBuffer;
  23664. }());
  23665. BABYLON.VertexBuffer = VertexBuffer;
  23666. })(BABYLON || (BABYLON = {}));
  23667. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23668. var BABYLON;
  23669. (function (BABYLON) {
  23670. var InternalTexture = /** @class */ (function () {
  23671. function InternalTexture(engine, dataSource) {
  23672. this.onLoadedObservable = new BABYLON.Observable();
  23673. // Private
  23674. this._initialSlot = -1;
  23675. this._designatedSlot = -1;
  23676. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23677. this._references = 1;
  23678. this._engine = engine;
  23679. this._dataSource = dataSource;
  23680. this._webGLTexture = engine._createTexture();
  23681. }
  23682. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23683. get: function () {
  23684. return this._dataSource;
  23685. },
  23686. enumerable: true,
  23687. configurable: true
  23688. });
  23689. InternalTexture.prototype.incrementReferences = function () {
  23690. this._references++;
  23691. };
  23692. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23693. if (depth === void 0) { depth = 1; }
  23694. this.width = width;
  23695. this.height = height;
  23696. this.depth = depth;
  23697. this.baseWidth = width;
  23698. this.baseHeight = height;
  23699. this.baseDepth = depth;
  23700. this._size = width * height * depth;
  23701. };
  23702. InternalTexture.prototype._rebuild = function () {
  23703. var _this = this;
  23704. var proxy;
  23705. this.isReady = false;
  23706. this._cachedCoordinatesMode = null;
  23707. this._cachedWrapU = null;
  23708. this._cachedWrapV = null;
  23709. this._cachedAnisotropicFilteringLevel = null;
  23710. switch (this._dataSource) {
  23711. case InternalTexture.DATASOURCE_TEMP:
  23712. return;
  23713. case InternalTexture.DATASOURCE_URL:
  23714. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23715. _this.isReady = true;
  23716. }, null, this._buffer, undefined, this.format);
  23717. proxy._swapAndDie(this);
  23718. return;
  23719. case InternalTexture.DATASOURCE_RAW:
  23720. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23721. proxy._swapAndDie(this);
  23722. this.isReady = true;
  23723. return;
  23724. case InternalTexture.DATASOURCE_RAW3D:
  23725. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23726. proxy._swapAndDie(this);
  23727. this.isReady = true;
  23728. return;
  23729. case InternalTexture.DATASOURCE_DYNAMIC:
  23730. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23731. proxy._swapAndDie(this);
  23732. // The engine will make sure to update content so no need to flag it as isReady = true
  23733. return;
  23734. case InternalTexture.DATASOURCE_RENDERTARGET:
  23735. var options = new BABYLON.RenderTargetCreationOptions();
  23736. options.generateDepthBuffer = this._generateDepthBuffer;
  23737. options.generateMipMaps = this.generateMipMaps;
  23738. options.generateStencilBuffer = this._generateStencilBuffer;
  23739. options.samplingMode = this.samplingMode;
  23740. options.type = this.type;
  23741. if (this.isCube) {
  23742. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23743. }
  23744. else {
  23745. var size = {
  23746. width: this.width,
  23747. height: this.height
  23748. };
  23749. proxy = this._engine.createRenderTargetTexture(size, options);
  23750. }
  23751. proxy._swapAndDie(this);
  23752. this.isReady = true;
  23753. return;
  23754. case InternalTexture.DATASOURCE_CUBE:
  23755. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23756. _this.isReady = true;
  23757. }, null, this.format, this._extension);
  23758. proxy._swapAndDie(this);
  23759. return;
  23760. case InternalTexture.DATASOURCE_CUBERAW:
  23761. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23762. proxy._swapAndDie(this);
  23763. this.isReady = true;
  23764. return;
  23765. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23766. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23767. if (proxy) {
  23768. proxy._swapAndDie(_this);
  23769. }
  23770. _this.isReady = true;
  23771. }, null, this.format, this._extension);
  23772. return;
  23773. }
  23774. };
  23775. InternalTexture.prototype._swapAndDie = function (target) {
  23776. target._webGLTexture = this._webGLTexture;
  23777. if (this._framebuffer) {
  23778. target._framebuffer = this._framebuffer;
  23779. }
  23780. if (this._depthStencilBuffer) {
  23781. target._depthStencilBuffer = this._depthStencilBuffer;
  23782. }
  23783. if (this._lodTextureHigh) {
  23784. if (target._lodTextureHigh) {
  23785. target._lodTextureHigh.dispose();
  23786. }
  23787. target._lodTextureHigh = this._lodTextureHigh;
  23788. }
  23789. if (this._lodTextureMid) {
  23790. if (target._lodTextureMid) {
  23791. target._lodTextureMid.dispose();
  23792. }
  23793. target._lodTextureMid = this._lodTextureMid;
  23794. }
  23795. if (this._lodTextureLow) {
  23796. if (target._lodTextureLow) {
  23797. target._lodTextureLow.dispose();
  23798. }
  23799. target._lodTextureLow = this._lodTextureLow;
  23800. }
  23801. var cache = this._engine.getLoadedTexturesCache();
  23802. var index = cache.indexOf(this);
  23803. if (index !== -1) {
  23804. cache.splice(index, 1);
  23805. }
  23806. };
  23807. InternalTexture.prototype.dispose = function () {
  23808. if (!this._webGLTexture) {
  23809. return;
  23810. }
  23811. this._references--;
  23812. if (this._references === 0) {
  23813. this._engine._releaseTexture(this);
  23814. this._webGLTexture = null;
  23815. }
  23816. };
  23817. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23818. InternalTexture.DATASOURCE_URL = 1;
  23819. InternalTexture.DATASOURCE_TEMP = 2;
  23820. InternalTexture.DATASOURCE_RAW = 3;
  23821. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23822. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23823. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23824. InternalTexture.DATASOURCE_CUBE = 7;
  23825. InternalTexture.DATASOURCE_CUBERAW = 8;
  23826. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23827. InternalTexture.DATASOURCE_RAW3D = 10;
  23828. return InternalTexture;
  23829. }());
  23830. BABYLON.InternalTexture = InternalTexture;
  23831. })(BABYLON || (BABYLON = {}));
  23832. //# sourceMappingURL=babylon.internalTexture.js.map
  23833. var BABYLON;
  23834. (function (BABYLON) {
  23835. var BaseTexture = /** @class */ (function () {
  23836. function BaseTexture(scene) {
  23837. this._hasAlpha = false;
  23838. this.getAlphaFromRGB = false;
  23839. this.level = 1;
  23840. this.coordinatesIndex = 0;
  23841. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23842. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23843. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23844. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23845. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23846. this.isCube = false;
  23847. this.is3D = false;
  23848. this.gammaSpace = true;
  23849. this.invertZ = false;
  23850. this.lodLevelInAlpha = false;
  23851. this.lodGenerationOffset = 0.0;
  23852. this.lodGenerationScale = 0.8;
  23853. this.isRenderTarget = false;
  23854. this.animations = new Array();
  23855. /**
  23856. * An event triggered when the texture is disposed.
  23857. * @type {BABYLON.Observable}
  23858. */
  23859. this.onDisposeObservable = new BABYLON.Observable();
  23860. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23861. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23862. if (this._scene) {
  23863. this._scene.textures.push(this);
  23864. }
  23865. this._uid = null;
  23866. }
  23867. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23868. get: function () {
  23869. return this._hasAlpha;
  23870. },
  23871. set: function (value) {
  23872. if (this._hasAlpha === value) {
  23873. return;
  23874. }
  23875. this._hasAlpha = value;
  23876. if (this._scene) {
  23877. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23878. }
  23879. },
  23880. enumerable: true,
  23881. configurable: true
  23882. });
  23883. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23884. get: function () {
  23885. return this._coordinatesMode;
  23886. },
  23887. set: function (value) {
  23888. if (this._coordinatesMode === value) {
  23889. return;
  23890. }
  23891. this._coordinatesMode = value;
  23892. if (this._scene) {
  23893. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23894. }
  23895. },
  23896. enumerable: true,
  23897. configurable: true
  23898. });
  23899. Object.defineProperty(BaseTexture.prototype, "uid", {
  23900. get: function () {
  23901. if (!this._uid) {
  23902. this._uid = BABYLON.Tools.RandomId();
  23903. }
  23904. return this._uid;
  23905. },
  23906. enumerable: true,
  23907. configurable: true
  23908. });
  23909. BaseTexture.prototype.toString = function () {
  23910. return this.name;
  23911. };
  23912. BaseTexture.prototype.getClassName = function () {
  23913. return "BaseTexture";
  23914. };
  23915. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23916. set: function (callback) {
  23917. if (this._onDisposeObserver) {
  23918. this.onDisposeObservable.remove(this._onDisposeObserver);
  23919. }
  23920. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23921. },
  23922. enumerable: true,
  23923. configurable: true
  23924. });
  23925. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23926. get: function () {
  23927. return true;
  23928. },
  23929. enumerable: true,
  23930. configurable: true
  23931. });
  23932. BaseTexture.prototype.getScene = function () {
  23933. return this._scene;
  23934. };
  23935. BaseTexture.prototype.getTextureMatrix = function () {
  23936. return BABYLON.Matrix.IdentityReadOnly;
  23937. };
  23938. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23939. return BABYLON.Matrix.IdentityReadOnly;
  23940. };
  23941. BaseTexture.prototype.getInternalTexture = function () {
  23942. return this._texture;
  23943. };
  23944. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23945. return !this.isBlocking || this.isReady();
  23946. };
  23947. BaseTexture.prototype.isReady = function () {
  23948. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23949. this.delayLoad();
  23950. return false;
  23951. }
  23952. if (this._texture) {
  23953. return this._texture.isReady;
  23954. }
  23955. return false;
  23956. };
  23957. BaseTexture.prototype.getSize = function () {
  23958. if (this._texture && this._texture.width) {
  23959. return new BABYLON.Size(this._texture.width, this._texture.height);
  23960. }
  23961. if (this._texture && this._texture._size) {
  23962. return new BABYLON.Size(this._texture._size, this._texture._size);
  23963. }
  23964. return BABYLON.Size.Zero();
  23965. };
  23966. BaseTexture.prototype.getBaseSize = function () {
  23967. if (!this.isReady() || !this._texture)
  23968. return BABYLON.Size.Zero();
  23969. if (this._texture._size) {
  23970. return new BABYLON.Size(this._texture._size, this._texture._size);
  23971. }
  23972. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23973. };
  23974. BaseTexture.prototype.scale = function (ratio) {
  23975. };
  23976. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23977. get: function () {
  23978. return false;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23984. if (!this._scene) {
  23985. return null;
  23986. }
  23987. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23988. for (var index = 0; index < texturesCache.length; index++) {
  23989. var texturesCacheEntry = texturesCache[index];
  23990. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23991. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23992. texturesCacheEntry.incrementReferences();
  23993. return texturesCacheEntry;
  23994. }
  23995. }
  23996. }
  23997. return null;
  23998. };
  23999. BaseTexture.prototype._rebuild = function () {
  24000. };
  24001. BaseTexture.prototype.delayLoad = function () {
  24002. };
  24003. BaseTexture.prototype.clone = function () {
  24004. return null;
  24005. };
  24006. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24007. get: function () {
  24008. if (!this._texture) {
  24009. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24010. }
  24011. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24012. },
  24013. enumerable: true,
  24014. configurable: true
  24015. });
  24016. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24017. get: function () {
  24018. if (!this._texture) {
  24019. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24020. }
  24021. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24022. },
  24023. enumerable: true,
  24024. configurable: true
  24025. });
  24026. BaseTexture.prototype.readPixels = function (faceIndex) {
  24027. if (faceIndex === void 0) { faceIndex = 0; }
  24028. if (!this._texture) {
  24029. return null;
  24030. }
  24031. var size = this.getSize();
  24032. var scene = this.getScene();
  24033. if (!scene) {
  24034. return null;
  24035. }
  24036. var engine = scene.getEngine();
  24037. if (this._texture.isCube) {
  24038. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24039. }
  24040. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24041. };
  24042. BaseTexture.prototype.releaseInternalTexture = function () {
  24043. if (this._texture) {
  24044. this._texture.dispose();
  24045. this._texture = null;
  24046. }
  24047. };
  24048. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24049. get: function () {
  24050. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24051. return null;
  24052. }
  24053. if (!this._texture._sphericalPolynomial) {
  24054. this._texture._sphericalPolynomial =
  24055. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24056. }
  24057. return this._texture._sphericalPolynomial;
  24058. },
  24059. set: function (value) {
  24060. if (this._texture) {
  24061. this._texture._sphericalPolynomial = value;
  24062. }
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24068. get: function () {
  24069. if (this._texture) {
  24070. return this._texture._lodTextureHigh;
  24071. }
  24072. return null;
  24073. },
  24074. enumerable: true,
  24075. configurable: true
  24076. });
  24077. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24078. get: function () {
  24079. if (this._texture) {
  24080. return this._texture._lodTextureMid;
  24081. }
  24082. return null;
  24083. },
  24084. enumerable: true,
  24085. configurable: true
  24086. });
  24087. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24088. get: function () {
  24089. if (this._texture) {
  24090. return this._texture._lodTextureLow;
  24091. }
  24092. return null;
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. BaseTexture.prototype.dispose = function () {
  24098. if (!this._scene) {
  24099. return;
  24100. }
  24101. // Animations
  24102. this._scene.stopAnimation(this);
  24103. // Remove from scene
  24104. this._scene._removePendingData(this);
  24105. var index = this._scene.textures.indexOf(this);
  24106. if (index >= 0) {
  24107. this._scene.textures.splice(index, 1);
  24108. }
  24109. if (this._texture === undefined) {
  24110. return;
  24111. }
  24112. // Release
  24113. this.releaseInternalTexture();
  24114. // Callback
  24115. this.onDisposeObservable.notifyObservers(this);
  24116. this.onDisposeObservable.clear();
  24117. };
  24118. BaseTexture.prototype.serialize = function () {
  24119. if (!this.name) {
  24120. return null;
  24121. }
  24122. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24123. // Animations
  24124. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24125. return serializationObject;
  24126. };
  24127. BaseTexture.WhenAllReady = function (textures, callback) {
  24128. var numRemaining = textures.length;
  24129. if (numRemaining === 0) {
  24130. callback();
  24131. return;
  24132. }
  24133. var _loop_1 = function () {
  24134. texture = textures[i];
  24135. if (texture.isReady()) {
  24136. if (--numRemaining === 0) {
  24137. callback();
  24138. }
  24139. }
  24140. else {
  24141. onLoadObservable = texture.onLoadObservable;
  24142. var onLoadCallback_1 = function () {
  24143. onLoadObservable.removeCallback(onLoadCallback_1);
  24144. if (--numRemaining === 0) {
  24145. callback();
  24146. }
  24147. };
  24148. onLoadObservable.add(onLoadCallback_1);
  24149. }
  24150. };
  24151. var texture, onLoadObservable;
  24152. for (var i = 0; i < textures.length; i++) {
  24153. _loop_1();
  24154. }
  24155. };
  24156. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24157. __decorate([
  24158. BABYLON.serialize()
  24159. ], BaseTexture.prototype, "name", void 0);
  24160. __decorate([
  24161. BABYLON.serialize("hasAlpha")
  24162. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24163. __decorate([
  24164. BABYLON.serialize()
  24165. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24166. __decorate([
  24167. BABYLON.serialize()
  24168. ], BaseTexture.prototype, "level", void 0);
  24169. __decorate([
  24170. BABYLON.serialize()
  24171. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24172. __decorate([
  24173. BABYLON.serialize("coordinatesMode")
  24174. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24175. __decorate([
  24176. BABYLON.serialize()
  24177. ], BaseTexture.prototype, "wrapU", void 0);
  24178. __decorate([
  24179. BABYLON.serialize()
  24180. ], BaseTexture.prototype, "wrapV", void 0);
  24181. __decorate([
  24182. BABYLON.serialize()
  24183. ], BaseTexture.prototype, "wrapR", void 0);
  24184. __decorate([
  24185. BABYLON.serialize()
  24186. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24187. __decorate([
  24188. BABYLON.serialize()
  24189. ], BaseTexture.prototype, "isCube", void 0);
  24190. __decorate([
  24191. BABYLON.serialize()
  24192. ], BaseTexture.prototype, "is3D", void 0);
  24193. __decorate([
  24194. BABYLON.serialize()
  24195. ], BaseTexture.prototype, "gammaSpace", void 0);
  24196. __decorate([
  24197. BABYLON.serialize()
  24198. ], BaseTexture.prototype, "invertZ", void 0);
  24199. __decorate([
  24200. BABYLON.serialize()
  24201. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24202. __decorate([
  24203. BABYLON.serialize()
  24204. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24205. __decorate([
  24206. BABYLON.serialize()
  24207. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24208. __decorate([
  24209. BABYLON.serialize()
  24210. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24211. return BaseTexture;
  24212. }());
  24213. BABYLON.BaseTexture = BaseTexture;
  24214. })(BABYLON || (BABYLON = {}));
  24215. //# sourceMappingURL=babylon.baseTexture.js.map
  24216. var BABYLON;
  24217. (function (BABYLON) {
  24218. var Texture = /** @class */ (function (_super) {
  24219. __extends(Texture, _super);
  24220. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24221. if (noMipmap === void 0) { noMipmap = false; }
  24222. if (invertY === void 0) { invertY = true; }
  24223. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24224. if (onLoad === void 0) { onLoad = null; }
  24225. if (onError === void 0) { onError = null; }
  24226. if (buffer === void 0) { buffer = null; }
  24227. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24228. var _this = _super.call(this, scene) || this;
  24229. _this.uOffset = 0;
  24230. _this.vOffset = 0;
  24231. _this.uScale = 1.0;
  24232. _this.vScale = 1.0;
  24233. _this.uAng = 0;
  24234. _this.vAng = 0;
  24235. _this.wAng = 0;
  24236. _this._isBlocking = true;
  24237. _this.name = url || "";
  24238. _this.url = url;
  24239. _this._noMipmap = noMipmap;
  24240. _this._invertY = invertY;
  24241. _this._samplingMode = samplingMode;
  24242. _this._buffer = buffer;
  24243. _this._deleteBuffer = deleteBuffer;
  24244. if (format) {
  24245. _this._format = format;
  24246. }
  24247. scene = _this.getScene();
  24248. if (!scene) {
  24249. return _this;
  24250. }
  24251. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24252. var load = function () {
  24253. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24254. _this.onLoadObservable.notifyObservers(_this);
  24255. }
  24256. if (onLoad) {
  24257. onLoad();
  24258. }
  24259. if (!_this.isBlocking && scene) {
  24260. scene.resetCachedMaterial();
  24261. }
  24262. };
  24263. if (!_this.url) {
  24264. _this._delayedOnLoad = load;
  24265. _this._delayedOnError = onError;
  24266. return _this;
  24267. }
  24268. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24269. if (!_this._texture) {
  24270. if (!scene.useDelayedTextureLoading) {
  24271. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24272. if (deleteBuffer) {
  24273. delete _this._buffer;
  24274. }
  24275. }
  24276. else {
  24277. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24278. _this._delayedOnLoad = load;
  24279. _this._delayedOnError = onError;
  24280. }
  24281. }
  24282. else {
  24283. if (_this._texture.isReady) {
  24284. BABYLON.Tools.SetImmediate(function () { return load(); });
  24285. }
  24286. else {
  24287. _this._texture.onLoadedObservable.add(load);
  24288. }
  24289. }
  24290. return _this;
  24291. }
  24292. Object.defineProperty(Texture.prototype, "noMipmap", {
  24293. get: function () {
  24294. return this._noMipmap;
  24295. },
  24296. enumerable: true,
  24297. configurable: true
  24298. });
  24299. Object.defineProperty(Texture.prototype, "isBlocking", {
  24300. get: function () {
  24301. return this._isBlocking;
  24302. },
  24303. set: function (value) {
  24304. this._isBlocking = value;
  24305. },
  24306. enumerable: true,
  24307. configurable: true
  24308. });
  24309. Object.defineProperty(Texture.prototype, "samplingMode", {
  24310. get: function () {
  24311. return this._samplingMode;
  24312. },
  24313. enumerable: true,
  24314. configurable: true
  24315. });
  24316. Texture.prototype.updateURL = function (url) {
  24317. this.url = url;
  24318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24319. this.delayLoad();
  24320. };
  24321. Texture.prototype.delayLoad = function () {
  24322. var _this = this;
  24323. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24324. return;
  24325. }
  24326. var scene = this.getScene();
  24327. if (!scene) {
  24328. return;
  24329. }
  24330. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24331. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24332. if (!this._texture) {
  24333. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24334. if (this._deleteBuffer) {
  24335. delete this._buffer;
  24336. }
  24337. }
  24338. else {
  24339. if (this._texture.isReady) {
  24340. BABYLON.Tools.SetImmediate(function () {
  24341. if (!_this._delayedOnLoad) {
  24342. return;
  24343. }
  24344. _this._delayedOnLoad();
  24345. });
  24346. }
  24347. else {
  24348. if (this._delayedOnLoad) {
  24349. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24350. }
  24351. }
  24352. }
  24353. };
  24354. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24355. if (!this._texture) {
  24356. return;
  24357. }
  24358. var scene = this.getScene();
  24359. if (!scene) {
  24360. return;
  24361. }
  24362. this._samplingMode = samplingMode;
  24363. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24364. };
  24365. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24366. x *= this.uScale;
  24367. y *= this.vScale;
  24368. x -= 0.5 * this.uScale;
  24369. y -= 0.5 * this.vScale;
  24370. z -= 0.5;
  24371. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24372. t.x += 0.5 * this.uScale + this.uOffset;
  24373. t.y += 0.5 * this.vScale + this.vOffset;
  24374. t.z += 0.5;
  24375. };
  24376. Texture.prototype.getTextureMatrix = function () {
  24377. var _this = this;
  24378. if (this.uOffset === this._cachedUOffset &&
  24379. this.vOffset === this._cachedVOffset &&
  24380. this.uScale === this._cachedUScale &&
  24381. this.vScale === this._cachedVScale &&
  24382. this.uAng === this._cachedUAng &&
  24383. this.vAng === this._cachedVAng &&
  24384. this.wAng === this._cachedWAng) {
  24385. return this._cachedTextureMatrix;
  24386. }
  24387. this._cachedUOffset = this.uOffset;
  24388. this._cachedVOffset = this.vOffset;
  24389. this._cachedUScale = this.uScale;
  24390. this._cachedVScale = this.vScale;
  24391. this._cachedUAng = this.uAng;
  24392. this._cachedVAng = this.vAng;
  24393. this._cachedWAng = this.wAng;
  24394. if (!this._cachedTextureMatrix) {
  24395. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24396. this._rowGenerationMatrix = new BABYLON.Matrix();
  24397. this._t0 = BABYLON.Vector3.Zero();
  24398. this._t1 = BABYLON.Vector3.Zero();
  24399. this._t2 = BABYLON.Vector3.Zero();
  24400. }
  24401. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24402. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24403. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24404. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24405. this._t1.subtractInPlace(this._t0);
  24406. this._t2.subtractInPlace(this._t0);
  24407. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24408. this._cachedTextureMatrix.m[0] = this._t1.x;
  24409. this._cachedTextureMatrix.m[1] = this._t1.y;
  24410. this._cachedTextureMatrix.m[2] = this._t1.z;
  24411. this._cachedTextureMatrix.m[4] = this._t2.x;
  24412. this._cachedTextureMatrix.m[5] = this._t2.y;
  24413. this._cachedTextureMatrix.m[6] = this._t2.z;
  24414. this._cachedTextureMatrix.m[8] = this._t0.x;
  24415. this._cachedTextureMatrix.m[9] = this._t0.y;
  24416. this._cachedTextureMatrix.m[10] = this._t0.z;
  24417. var scene = this.getScene();
  24418. if (!scene) {
  24419. return this._cachedTextureMatrix;
  24420. }
  24421. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24422. return mat.hasTexture(_this);
  24423. });
  24424. return this._cachedTextureMatrix;
  24425. };
  24426. Texture.prototype.getReflectionTextureMatrix = function () {
  24427. var _this = this;
  24428. var scene = this.getScene();
  24429. if (!scene) {
  24430. return this._cachedTextureMatrix;
  24431. }
  24432. if (this.uOffset === this._cachedUOffset &&
  24433. this.vOffset === this._cachedVOffset &&
  24434. this.uScale === this._cachedUScale &&
  24435. this.vScale === this._cachedVScale &&
  24436. this.coordinatesMode === this._cachedCoordinatesMode) {
  24437. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24438. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24439. return this._cachedTextureMatrix;
  24440. }
  24441. }
  24442. else {
  24443. return this._cachedTextureMatrix;
  24444. }
  24445. }
  24446. if (!this._cachedTextureMatrix) {
  24447. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24448. }
  24449. if (!this._projectionModeMatrix) {
  24450. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24451. }
  24452. this._cachedUOffset = this.uOffset;
  24453. this._cachedVOffset = this.vOffset;
  24454. this._cachedUScale = this.uScale;
  24455. this._cachedVScale = this.vScale;
  24456. this._cachedCoordinatesMode = this.coordinatesMode;
  24457. switch (this.coordinatesMode) {
  24458. case Texture.PLANAR_MODE:
  24459. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24460. this._cachedTextureMatrix[0] = this.uScale;
  24461. this._cachedTextureMatrix[5] = this.vScale;
  24462. this._cachedTextureMatrix[12] = this.uOffset;
  24463. this._cachedTextureMatrix[13] = this.vOffset;
  24464. break;
  24465. case Texture.PROJECTION_MODE:
  24466. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24467. this._projectionModeMatrix.m[0] = 0.5;
  24468. this._projectionModeMatrix.m[5] = -0.5;
  24469. this._projectionModeMatrix.m[10] = 0.0;
  24470. this._projectionModeMatrix.m[12] = 0.5;
  24471. this._projectionModeMatrix.m[13] = 0.5;
  24472. this._projectionModeMatrix.m[14] = 1.0;
  24473. this._projectionModeMatrix.m[15] = 1.0;
  24474. var projectionMatrix = scene.getProjectionMatrix();
  24475. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24476. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24477. break;
  24478. default:
  24479. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24480. break;
  24481. }
  24482. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24483. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24484. });
  24485. return this._cachedTextureMatrix;
  24486. };
  24487. Texture.prototype.clone = function () {
  24488. var _this = this;
  24489. return BABYLON.SerializationHelper.Clone(function () {
  24490. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24491. }, this);
  24492. };
  24493. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24494. get: function () {
  24495. if (!this._onLoadObservable) {
  24496. this._onLoadObservable = new BABYLON.Observable();
  24497. }
  24498. return this._onLoadObservable;
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Texture.prototype.serialize = function () {
  24504. var serializationObject = _super.prototype.serialize.call(this);
  24505. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24506. serializationObject.base64String = this._buffer;
  24507. serializationObject.name = serializationObject.name.replace("data:", "");
  24508. }
  24509. return serializationObject;
  24510. };
  24511. Texture.prototype.getClassName = function () {
  24512. return "Texture";
  24513. };
  24514. Texture.prototype.dispose = function () {
  24515. _super.prototype.dispose.call(this);
  24516. if (this.onLoadObservable) {
  24517. this.onLoadObservable.clear();
  24518. this._onLoadObservable = null;
  24519. }
  24520. this._delayedOnLoad = null;
  24521. this._delayedOnError = null;
  24522. };
  24523. // Statics
  24524. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24525. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24526. if (onLoad === void 0) { onLoad = null; }
  24527. if (onError === void 0) { onError = null; }
  24528. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24529. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24530. };
  24531. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24532. if (parsedTexture.customType) {
  24533. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24534. // Update Sampling Mode
  24535. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24536. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24537. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24538. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24539. }
  24540. }
  24541. return parsedCustomTexture;
  24542. }
  24543. if (parsedTexture.isCube) {
  24544. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24545. }
  24546. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24547. return null;
  24548. }
  24549. var texture = BABYLON.SerializationHelper.Parse(function () {
  24550. var generateMipMaps = true;
  24551. if (parsedTexture.noMipmap) {
  24552. generateMipMaps = false;
  24553. }
  24554. if (parsedTexture.mirrorPlane) {
  24555. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24556. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24557. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24558. return mirrorTexture;
  24559. }
  24560. else if (parsedTexture.isRenderTarget) {
  24561. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24562. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24563. return renderTargetTexture;
  24564. }
  24565. else {
  24566. var texture;
  24567. if (parsedTexture.base64String) {
  24568. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24569. }
  24570. else {
  24571. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24572. }
  24573. return texture;
  24574. }
  24575. }, parsedTexture, scene);
  24576. // Update Sampling Mode
  24577. if (parsedTexture.samplingMode) {
  24578. var sampling = parsedTexture.samplingMode;
  24579. if (texture._samplingMode !== sampling) {
  24580. texture.updateSamplingMode(sampling);
  24581. }
  24582. }
  24583. // Animations
  24584. if (parsedTexture.animations) {
  24585. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24586. var parsedAnimation = parsedTexture.animations[animationIndex];
  24587. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24588. }
  24589. }
  24590. return texture;
  24591. };
  24592. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24593. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24594. if (noMipmap === void 0) { noMipmap = false; }
  24595. if (invertY === void 0) { invertY = true; }
  24596. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24597. if (onLoad === void 0) { onLoad = null; }
  24598. if (onError === void 0) { onError = null; }
  24599. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24600. if (name.substr(0, 5) !== "data:") {
  24601. name = "data:" + name;
  24602. }
  24603. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24604. };
  24605. // Constants
  24606. Texture.NEAREST_SAMPLINGMODE = 1;
  24607. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24608. Texture.BILINEAR_SAMPLINGMODE = 2;
  24609. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24610. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24611. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24612. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24613. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24614. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24615. Texture.NEAREST_LINEAR = 7;
  24616. Texture.NEAREST_NEAREST = 8;
  24617. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24618. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24619. Texture.LINEAR_LINEAR = 11;
  24620. Texture.LINEAR_NEAREST = 12;
  24621. Texture.EXPLICIT_MODE = 0;
  24622. Texture.SPHERICAL_MODE = 1;
  24623. Texture.PLANAR_MODE = 2;
  24624. Texture.CUBIC_MODE = 3;
  24625. Texture.PROJECTION_MODE = 4;
  24626. Texture.SKYBOX_MODE = 5;
  24627. Texture.INVCUBIC_MODE = 6;
  24628. Texture.EQUIRECTANGULAR_MODE = 7;
  24629. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24630. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24631. Texture.CLAMP_ADDRESSMODE = 0;
  24632. Texture.WRAP_ADDRESSMODE = 1;
  24633. Texture.MIRROR_ADDRESSMODE = 2;
  24634. __decorate([
  24635. BABYLON.serialize()
  24636. ], Texture.prototype, "url", void 0);
  24637. __decorate([
  24638. BABYLON.serialize()
  24639. ], Texture.prototype, "uOffset", void 0);
  24640. __decorate([
  24641. BABYLON.serialize()
  24642. ], Texture.prototype, "vOffset", void 0);
  24643. __decorate([
  24644. BABYLON.serialize()
  24645. ], Texture.prototype, "uScale", void 0);
  24646. __decorate([
  24647. BABYLON.serialize()
  24648. ], Texture.prototype, "vScale", void 0);
  24649. __decorate([
  24650. BABYLON.serialize()
  24651. ], Texture.prototype, "uAng", void 0);
  24652. __decorate([
  24653. BABYLON.serialize()
  24654. ], Texture.prototype, "vAng", void 0);
  24655. __decorate([
  24656. BABYLON.serialize()
  24657. ], Texture.prototype, "wAng", void 0);
  24658. __decorate([
  24659. BABYLON.serialize()
  24660. ], Texture.prototype, "isBlocking", null);
  24661. return Texture;
  24662. }(BABYLON.BaseTexture));
  24663. BABYLON.Texture = Texture;
  24664. })(BABYLON || (BABYLON = {}));
  24665. //# sourceMappingURL=babylon.texture.js.map
  24666. var BABYLON;
  24667. (function (BABYLON) {
  24668. var _InstancesBatch = /** @class */ (function () {
  24669. function _InstancesBatch() {
  24670. this.mustReturn = false;
  24671. this.visibleInstances = new Array();
  24672. this.renderSelf = new Array();
  24673. }
  24674. return _InstancesBatch;
  24675. }());
  24676. BABYLON._InstancesBatch = _InstancesBatch;
  24677. var Mesh = /** @class */ (function (_super) {
  24678. __extends(Mesh, _super);
  24679. /**
  24680. * @constructor
  24681. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24682. * @param {Scene} scene The scene to add this mesh to.
  24683. * @param {Node} parent The parent of this mesh, if it has one
  24684. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24685. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24686. * When false, achieved by calling a clone(), also passing False.
  24687. * This will make creation of children, recursive.
  24688. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24689. */
  24690. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24691. if (scene === void 0) { scene = null; }
  24692. if (parent === void 0) { parent = null; }
  24693. if (source === void 0) { source = null; }
  24694. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24695. var _this = _super.call(this, name, scene) || this;
  24696. // Events
  24697. /**
  24698. * An event triggered before rendering the mesh
  24699. * @type {BABYLON.Observable}
  24700. */
  24701. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24702. /**
  24703. * An event triggered after rendering the mesh
  24704. * @type {BABYLON.Observable}
  24705. */
  24706. _this.onAfterRenderObservable = new BABYLON.Observable();
  24707. /**
  24708. * An event triggered before drawing the mesh
  24709. * @type {BABYLON.Observable}
  24710. */
  24711. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24712. // Members
  24713. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24714. _this.instances = new Array();
  24715. _this._LODLevels = new Array();
  24716. _this._visibleInstances = {};
  24717. _this._renderIdForInstances = new Array();
  24718. _this._batchCache = new _InstancesBatch();
  24719. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24720. // Use by builder only to know what orientation were the mesh build in.
  24721. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24722. _this.overrideMaterialSideOrientation = null;
  24723. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24724. // Will be used to save a source mesh reference, If any
  24725. _this._source = null;
  24726. scene = _this.getScene();
  24727. if (source) {
  24728. // Source mesh
  24729. _this._source = source;
  24730. // Geometry
  24731. if (source._geometry) {
  24732. source._geometry.applyToMesh(_this);
  24733. }
  24734. // Deep copy
  24735. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24736. // Metadata
  24737. if (source.metadata && source.metadata.clone) {
  24738. _this.metadata = source.metadata.clone();
  24739. }
  24740. else {
  24741. _this.metadata = source.metadata;
  24742. }
  24743. // Tags
  24744. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24745. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24746. }
  24747. // Parent
  24748. _this.parent = source.parent;
  24749. // Pivot
  24750. _this.setPivotMatrix(source.getPivotMatrix());
  24751. _this.id = name + "." + source.id;
  24752. // Material
  24753. _this.material = source.material;
  24754. var index;
  24755. if (!doNotCloneChildren) {
  24756. // Children
  24757. var directDescendants = source.getDescendants(true);
  24758. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24759. var child = directDescendants[index_1];
  24760. if (child.clone) {
  24761. child.clone(name + "." + child.name, _this);
  24762. }
  24763. }
  24764. }
  24765. // Physics clone
  24766. var physicsEngine = _this.getScene().getPhysicsEngine();
  24767. if (clonePhysicsImpostor && physicsEngine) {
  24768. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24769. if (impostor) {
  24770. _this.physicsImpostor = impostor.clone(_this);
  24771. }
  24772. }
  24773. // Particles
  24774. for (index = 0; index < scene.particleSystems.length; index++) {
  24775. var system = scene.particleSystems[index];
  24776. if (system.emitter === source) {
  24777. system.clone(system.name, _this);
  24778. }
  24779. }
  24780. _this.computeWorldMatrix(true);
  24781. }
  24782. // Parent
  24783. if (parent !== null) {
  24784. _this.parent = parent;
  24785. }
  24786. return _this;
  24787. }
  24788. Object.defineProperty(Mesh, "FRONTSIDE", {
  24789. /**
  24790. * Mesh side orientation : usually the external or front surface
  24791. */
  24792. get: function () {
  24793. return Mesh._FRONTSIDE;
  24794. },
  24795. enumerable: true,
  24796. configurable: true
  24797. });
  24798. Object.defineProperty(Mesh, "BACKSIDE", {
  24799. /**
  24800. * Mesh side orientation : usually the internal or back surface
  24801. */
  24802. get: function () {
  24803. return Mesh._BACKSIDE;
  24804. },
  24805. enumerable: true,
  24806. configurable: true
  24807. });
  24808. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24809. /**
  24810. * Mesh side orientation : both internal and external or front and back surfaces
  24811. */
  24812. get: function () {
  24813. return Mesh._DOUBLESIDE;
  24814. },
  24815. enumerable: true,
  24816. configurable: true
  24817. });
  24818. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24819. /**
  24820. * Mesh side orientation : by default, `FRONTSIDE`
  24821. */
  24822. get: function () {
  24823. return Mesh._DEFAULTSIDE;
  24824. },
  24825. enumerable: true,
  24826. configurable: true
  24827. });
  24828. Object.defineProperty(Mesh, "NO_CAP", {
  24829. /**
  24830. * Mesh cap setting : no cap
  24831. */
  24832. get: function () {
  24833. return Mesh._NO_CAP;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Object.defineProperty(Mesh, "CAP_START", {
  24839. /**
  24840. * Mesh cap setting : one cap at the beginning of the mesh
  24841. */
  24842. get: function () {
  24843. return Mesh._CAP_START;
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(Mesh, "CAP_END", {
  24849. /**
  24850. * Mesh cap setting : one cap at the end of the mesh
  24851. */
  24852. get: function () {
  24853. return Mesh._CAP_END;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. Object.defineProperty(Mesh, "CAP_ALL", {
  24859. /**
  24860. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24861. */
  24862. get: function () {
  24863. return Mesh._CAP_ALL;
  24864. },
  24865. enumerable: true,
  24866. configurable: true
  24867. });
  24868. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24869. set: function (callback) {
  24870. if (this._onBeforeDrawObserver) {
  24871. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24872. }
  24873. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24874. },
  24875. enumerable: true,
  24876. configurable: true
  24877. });
  24878. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24879. get: function () {
  24880. return this._morphTargetManager;
  24881. },
  24882. set: function (value) {
  24883. if (this._morphTargetManager === value) {
  24884. return;
  24885. }
  24886. this._morphTargetManager = value;
  24887. this._syncGeometryWithMorphTargetManager();
  24888. },
  24889. enumerable: true,
  24890. configurable: true
  24891. });
  24892. Object.defineProperty(Mesh.prototype, "source", {
  24893. get: function () {
  24894. return this._source;
  24895. },
  24896. enumerable: true,
  24897. configurable: true
  24898. });
  24899. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24900. get: function () {
  24901. return this._unIndexed;
  24902. },
  24903. set: function (value) {
  24904. if (this._unIndexed !== value) {
  24905. this._unIndexed = value;
  24906. this._markSubMeshesAsAttributesDirty();
  24907. }
  24908. },
  24909. enumerable: true,
  24910. configurable: true
  24911. });
  24912. // Methods
  24913. /**
  24914. * Returns the string "Mesh".
  24915. */
  24916. Mesh.prototype.getClassName = function () {
  24917. return "Mesh";
  24918. };
  24919. /**
  24920. * Returns a string.
  24921. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24922. */
  24923. Mesh.prototype.toString = function (fullDetails) {
  24924. var ret = _super.prototype.toString.call(this, fullDetails);
  24925. ret += ", n vertices: " + this.getTotalVertices();
  24926. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24927. if (this.animations) {
  24928. for (var i = 0; i < this.animations.length; i++) {
  24929. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24930. }
  24931. }
  24932. if (fullDetails) {
  24933. if (this._geometry) {
  24934. var ib = this.getIndices();
  24935. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24936. if (vb && ib) {
  24937. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24938. }
  24939. }
  24940. else {
  24941. ret += ", flat shading: UNKNOWN";
  24942. }
  24943. }
  24944. return ret;
  24945. };
  24946. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24947. /**
  24948. * True if the mesh has some Levels Of Details (LOD).
  24949. * Returns a boolean.
  24950. */
  24951. get: function () {
  24952. return this._LODLevels.length > 0;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. Mesh.prototype._sortLODLevels = function () {
  24958. this._LODLevels.sort(function (a, b) {
  24959. if (a.distance < b.distance) {
  24960. return 1;
  24961. }
  24962. if (a.distance > b.distance) {
  24963. return -1;
  24964. }
  24965. return 0;
  24966. });
  24967. };
  24968. /**
  24969. * Add a mesh as LOD level triggered at the given distance.
  24970. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24971. * @param {number} distance The distance from the center of the object to show this level
  24972. * @param {Mesh} mesh The mesh to be added as LOD level
  24973. * @return {Mesh} This mesh (for chaining)
  24974. */
  24975. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24976. if (mesh && mesh._masterMesh) {
  24977. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24978. return this;
  24979. }
  24980. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24981. this._LODLevels.push(level);
  24982. if (mesh) {
  24983. mesh._masterMesh = this;
  24984. }
  24985. this._sortLODLevels();
  24986. return this;
  24987. };
  24988. /**
  24989. * Returns the LOD level mesh at the passed distance or null if not found.
  24990. * It is related to the method `addLODLevel(distance, mesh)`.
  24991. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24992. * Returns an object Mesh or `null`.
  24993. */
  24994. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24995. for (var index = 0; index < this._LODLevels.length; index++) {
  24996. var level = this._LODLevels[index];
  24997. if (level.distance === distance) {
  24998. return level.mesh;
  24999. }
  25000. }
  25001. return null;
  25002. };
  25003. /**
  25004. * Remove a mesh from the LOD array
  25005. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25006. * @param {Mesh} mesh The mesh to be removed.
  25007. * @return {Mesh} This mesh (for chaining)
  25008. */
  25009. Mesh.prototype.removeLODLevel = function (mesh) {
  25010. for (var index = 0; index < this._LODLevels.length; index++) {
  25011. if (this._LODLevels[index].mesh === mesh) {
  25012. this._LODLevels.splice(index, 1);
  25013. if (mesh) {
  25014. mesh._masterMesh = null;
  25015. }
  25016. }
  25017. }
  25018. this._sortLODLevels();
  25019. return this;
  25020. };
  25021. /**
  25022. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25023. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25024. */
  25025. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25026. if (!this._LODLevels || this._LODLevels.length === 0) {
  25027. return this;
  25028. }
  25029. var bSphere;
  25030. if (boundingSphere) {
  25031. bSphere = boundingSphere;
  25032. }
  25033. else {
  25034. var boundingInfo = this.getBoundingInfo();
  25035. bSphere = boundingInfo.boundingSphere;
  25036. }
  25037. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25038. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25039. if (this.onLODLevelSelection) {
  25040. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25041. }
  25042. return this;
  25043. }
  25044. for (var index = 0; index < this._LODLevels.length; index++) {
  25045. var level = this._LODLevels[index];
  25046. if (level.distance < distanceToCamera) {
  25047. if (level.mesh) {
  25048. level.mesh._preActivate();
  25049. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25050. }
  25051. if (this.onLODLevelSelection) {
  25052. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25053. }
  25054. return level.mesh;
  25055. }
  25056. }
  25057. if (this.onLODLevelSelection) {
  25058. this.onLODLevelSelection(distanceToCamera, this, this);
  25059. }
  25060. return this;
  25061. };
  25062. Object.defineProperty(Mesh.prototype, "geometry", {
  25063. /**
  25064. * Returns the mesh internal Geometry object.
  25065. */
  25066. get: function () {
  25067. return this._geometry;
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. /**
  25073. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25074. */
  25075. Mesh.prototype.getTotalVertices = function () {
  25076. if (this._geometry === null || this._geometry === undefined) {
  25077. return 0;
  25078. }
  25079. return this._geometry.getTotalVertices();
  25080. };
  25081. /**
  25082. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25083. * 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.
  25084. * You can force the copy with forceCopy === true
  25085. * Returns null if the mesh has no geometry or no vertex buffer.
  25086. * Possible `kind` values :
  25087. * - BABYLON.VertexBuffer.PositionKind
  25088. * - BABYLON.VertexBuffer.UVKind
  25089. * - BABYLON.VertexBuffer.UV2Kind
  25090. * - BABYLON.VertexBuffer.UV3Kind
  25091. * - BABYLON.VertexBuffer.UV4Kind
  25092. * - BABYLON.VertexBuffer.UV5Kind
  25093. * - BABYLON.VertexBuffer.UV6Kind
  25094. * - BABYLON.VertexBuffer.ColorKind
  25095. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25096. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25097. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25098. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25099. */
  25100. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25101. if (!this._geometry) {
  25102. return null;
  25103. }
  25104. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25105. };
  25106. /**
  25107. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25108. * Returns `null` if the mesh has no geometry.
  25109. * Possible `kind` values :
  25110. * - BABYLON.VertexBuffer.PositionKind
  25111. * - BABYLON.VertexBuffer.UVKind
  25112. * - BABYLON.VertexBuffer.UV2Kind
  25113. * - BABYLON.VertexBuffer.UV3Kind
  25114. * - BABYLON.VertexBuffer.UV4Kind
  25115. * - BABYLON.VertexBuffer.UV5Kind
  25116. * - BABYLON.VertexBuffer.UV6Kind
  25117. * - BABYLON.VertexBuffer.ColorKind
  25118. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25119. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25120. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25121. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25122. */
  25123. Mesh.prototype.getVertexBuffer = function (kind) {
  25124. if (!this._geometry) {
  25125. return null;
  25126. }
  25127. return this._geometry.getVertexBuffer(kind);
  25128. };
  25129. /**
  25130. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25131. * Possible `kind` values :
  25132. * - BABYLON.VertexBuffer.PositionKind
  25133. * - BABYLON.VertexBuffer.UVKind
  25134. * - BABYLON.VertexBuffer.UV2Kind
  25135. * - BABYLON.VertexBuffer.UV3Kind
  25136. * - BABYLON.VertexBuffer.UV4Kind
  25137. * - BABYLON.VertexBuffer.UV5Kind
  25138. * - BABYLON.VertexBuffer.UV6Kind
  25139. * - BABYLON.VertexBuffer.ColorKind
  25140. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25141. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25142. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25143. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25144. */
  25145. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25146. if (!this._geometry) {
  25147. if (this._delayInfo) {
  25148. return this._delayInfo.indexOf(kind) !== -1;
  25149. }
  25150. return false;
  25151. }
  25152. return this._geometry.isVerticesDataPresent(kind);
  25153. };
  25154. /**
  25155. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25156. * Possible `kind` values :
  25157. * - BABYLON.VertexBuffer.PositionKind
  25158. * - BABYLON.VertexBuffer.UVKind
  25159. * - BABYLON.VertexBuffer.UV2Kind
  25160. * - BABYLON.VertexBuffer.UV3Kind
  25161. * - BABYLON.VertexBuffer.UV4Kind
  25162. * - BABYLON.VertexBuffer.UV5Kind
  25163. * - BABYLON.VertexBuffer.UV6Kind
  25164. * - BABYLON.VertexBuffer.ColorKind
  25165. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25166. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25167. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25168. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25169. */
  25170. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25171. if (!this._geometry) {
  25172. if (this._delayInfo) {
  25173. return this._delayInfo.indexOf(kind) !== -1;
  25174. }
  25175. return false;
  25176. }
  25177. return this._geometry.isVertexBufferUpdatable(kind);
  25178. };
  25179. /**
  25180. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25181. * Possible `kind` values :
  25182. * - BABYLON.VertexBuffer.PositionKind
  25183. * - BABYLON.VertexBuffer.UVKind
  25184. * - BABYLON.VertexBuffer.UV2Kind
  25185. * - BABYLON.VertexBuffer.UV3Kind
  25186. * - BABYLON.VertexBuffer.UV4Kind
  25187. * - BABYLON.VertexBuffer.UV5Kind
  25188. * - BABYLON.VertexBuffer.UV6Kind
  25189. * - BABYLON.VertexBuffer.ColorKind
  25190. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25191. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25192. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25193. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25194. */
  25195. Mesh.prototype.getVerticesDataKinds = function () {
  25196. if (!this._geometry) {
  25197. var result = new Array();
  25198. if (this._delayInfo) {
  25199. this._delayInfo.forEach(function (kind, index, array) {
  25200. result.push(kind);
  25201. });
  25202. }
  25203. return result;
  25204. }
  25205. return this._geometry.getVerticesDataKinds();
  25206. };
  25207. /**
  25208. * Returns a positive integer : the total number of indices in this mesh geometry.
  25209. * Returns zero if the mesh has no geometry.
  25210. */
  25211. Mesh.prototype.getTotalIndices = function () {
  25212. if (!this._geometry) {
  25213. return 0;
  25214. }
  25215. return this._geometry.getTotalIndices();
  25216. };
  25217. /**
  25218. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25219. * 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.
  25220. * Returns an empty array if the mesh has no geometry.
  25221. */
  25222. Mesh.prototype.getIndices = function (copyWhenShared) {
  25223. if (!this._geometry) {
  25224. return [];
  25225. }
  25226. return this._geometry.getIndices(copyWhenShared);
  25227. };
  25228. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25229. get: function () {
  25230. return this._masterMesh !== null && this._masterMesh !== undefined;
  25231. },
  25232. enumerable: true,
  25233. configurable: true
  25234. });
  25235. /**
  25236. * Determine if the current mesh is ready to be rendered
  25237. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25238. * @returns true if all associated assets are ready (material, textures, shaders)
  25239. */
  25240. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25241. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25242. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25243. return false;
  25244. }
  25245. if (!_super.prototype.isReady.call(this)) {
  25246. return false;
  25247. }
  25248. if (!this.subMeshes || this.subMeshes.length === 0) {
  25249. return true;
  25250. }
  25251. var engine = this.getEngine();
  25252. var scene = this.getScene();
  25253. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25254. this.computeWorldMatrix();
  25255. var mat = this.material || scene.defaultMaterial;
  25256. if (mat) {
  25257. var currentAlphaTestingState = engine.getAlphaTesting();
  25258. if (mat.storeEffectOnSubMeshes) {
  25259. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25260. var subMesh = _a[_i];
  25261. var effectiveMaterial = subMesh.getMaterial();
  25262. if (effectiveMaterial) {
  25263. engine.setAlphaTesting(effectiveMaterial.needAlphaTesting() && !effectiveMaterial.needAlphaBlendingForMesh(this));
  25264. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25265. engine.setAlphaTesting(currentAlphaTestingState);
  25266. return false;
  25267. }
  25268. }
  25269. }
  25270. }
  25271. else {
  25272. engine.setAlphaTesting(mat.needAlphaTesting() && !mat.needAlphaBlendingForMesh(this));
  25273. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25274. engine.setAlphaTesting(currentAlphaTestingState);
  25275. return false;
  25276. }
  25277. }
  25278. engine.setAlphaTesting(currentAlphaTestingState);
  25279. }
  25280. // Shadows
  25281. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25282. var light = _c[_b];
  25283. var generator = light.getShadowGenerator();
  25284. if (generator) {
  25285. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25286. var subMesh = _e[_d];
  25287. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25288. return false;
  25289. }
  25290. }
  25291. }
  25292. }
  25293. // LOD
  25294. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25295. var lod = _g[_f];
  25296. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25297. return false;
  25298. }
  25299. }
  25300. return true;
  25301. };
  25302. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25303. /**
  25304. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25305. * This property is pertinent only for updatable parametric shapes.
  25306. */
  25307. get: function () {
  25308. return this._areNormalsFrozen;
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. /**
  25314. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25315. * It has no effect at all on other shapes.
  25316. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25317. * Returns the Mesh.
  25318. */
  25319. Mesh.prototype.freezeNormals = function () {
  25320. this._areNormalsFrozen = true;
  25321. return this;
  25322. };
  25323. /**
  25324. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25325. * It has no effect at all on other shapes.
  25326. * It reactivates the mesh normals computation if it was previously frozen.
  25327. * Returns the Mesh.
  25328. */
  25329. Mesh.prototype.unfreezeNormals = function () {
  25330. this._areNormalsFrozen = false;
  25331. return this;
  25332. };
  25333. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25334. /**
  25335. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25336. */
  25337. set: function (count) {
  25338. this._overridenInstanceCount = count;
  25339. },
  25340. enumerable: true,
  25341. configurable: true
  25342. });
  25343. // Methods
  25344. Mesh.prototype._preActivate = function () {
  25345. var sceneRenderId = this.getScene().getRenderId();
  25346. if (this._preActivateId === sceneRenderId) {
  25347. return this;
  25348. }
  25349. this._preActivateId = sceneRenderId;
  25350. this._visibleInstances = null;
  25351. return this;
  25352. };
  25353. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25354. if (this._visibleInstances) {
  25355. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25356. }
  25357. return this;
  25358. };
  25359. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25360. if (!this._visibleInstances) {
  25361. this._visibleInstances = {};
  25362. this._visibleInstances.defaultRenderId = renderId;
  25363. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25364. }
  25365. if (!this._visibleInstances[renderId]) {
  25366. this._visibleInstances[renderId] = new Array();
  25367. }
  25368. this._visibleInstances[renderId].push(instance);
  25369. return this;
  25370. };
  25371. /**
  25372. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25373. * This means the mesh underlying bounding box and sphere are recomputed.
  25374. * Returns the Mesh.
  25375. */
  25376. Mesh.prototype.refreshBoundingInfo = function () {
  25377. return this._refreshBoundingInfo(false);
  25378. };
  25379. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25380. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25381. return this;
  25382. }
  25383. var data = this._getPositionData(applySkeleton);
  25384. if (data) {
  25385. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25386. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25387. }
  25388. if (this.subMeshes) {
  25389. for (var index = 0; index < this.subMeshes.length; index++) {
  25390. this.subMeshes[index].refreshBoundingInfo();
  25391. }
  25392. }
  25393. this._updateBoundingInfo();
  25394. return this;
  25395. };
  25396. Mesh.prototype._getPositionData = function (applySkeleton) {
  25397. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25398. if (data && applySkeleton && this.skeleton) {
  25399. data = data.slice();
  25400. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25401. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25402. if (matricesWeightsData && matricesIndicesData) {
  25403. var needExtras = this.numBoneInfluencers > 4;
  25404. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25405. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25406. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25407. var tempVector = BABYLON.Tmp.Vector3[0];
  25408. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25409. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25410. var matWeightIdx = 0;
  25411. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25412. finalMatrix.reset();
  25413. var inf;
  25414. var weight;
  25415. for (inf = 0; inf < 4; inf++) {
  25416. weight = matricesWeightsData[matWeightIdx + inf];
  25417. if (weight <= 0)
  25418. break;
  25419. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25420. finalMatrix.addToSelf(tempMatrix);
  25421. }
  25422. if (needExtras) {
  25423. for (inf = 0; inf < 4; inf++) {
  25424. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25425. if (weight <= 0)
  25426. break;
  25427. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25428. finalMatrix.addToSelf(tempMatrix);
  25429. }
  25430. }
  25431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25432. tempVector.toArray(data, index);
  25433. }
  25434. }
  25435. }
  25436. return data;
  25437. };
  25438. Mesh.prototype._createGlobalSubMesh = function (force) {
  25439. var totalVertices = this.getTotalVertices();
  25440. if (!totalVertices || !this.getIndices()) {
  25441. return null;
  25442. }
  25443. // Check if we need to recreate the submeshes
  25444. if (this.subMeshes && this.subMeshes.length > 0) {
  25445. var ib = this.getIndices();
  25446. if (!ib) {
  25447. return null;
  25448. }
  25449. var totalIndices = ib.length;
  25450. var needToRecreate = false;
  25451. if (force) {
  25452. needToRecreate = true;
  25453. }
  25454. else {
  25455. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25456. var submesh = _a[_i];
  25457. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25458. needToRecreate = true;
  25459. break;
  25460. }
  25461. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25462. needToRecreate = true;
  25463. break;
  25464. }
  25465. }
  25466. }
  25467. if (!needToRecreate) {
  25468. return this.subMeshes[0];
  25469. }
  25470. }
  25471. this.releaseSubMeshes();
  25472. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25473. };
  25474. Mesh.prototype.subdivide = function (count) {
  25475. if (count < 1) {
  25476. return;
  25477. }
  25478. var totalIndices = this.getTotalIndices();
  25479. var subdivisionSize = (totalIndices / count) | 0;
  25480. var offset = 0;
  25481. // Ensure that subdivisionSize is a multiple of 3
  25482. while (subdivisionSize % 3 !== 0) {
  25483. subdivisionSize++;
  25484. }
  25485. this.releaseSubMeshes();
  25486. for (var index = 0; index < count; index++) {
  25487. if (offset >= totalIndices) {
  25488. break;
  25489. }
  25490. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25491. offset += subdivisionSize;
  25492. }
  25493. this.synchronizeInstances();
  25494. };
  25495. /**
  25496. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25497. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25498. * The `data` are either a numeric array either a Float32Array.
  25499. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25500. * 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).
  25501. * Note that a new underlying VertexBuffer object is created each call.
  25502. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25503. *
  25504. * Possible `kind` values :
  25505. * - BABYLON.VertexBuffer.PositionKind
  25506. * - BABYLON.VertexBuffer.UVKind
  25507. * - BABYLON.VertexBuffer.UV2Kind
  25508. * - BABYLON.VertexBuffer.UV3Kind
  25509. * - BABYLON.VertexBuffer.UV4Kind
  25510. * - BABYLON.VertexBuffer.UV5Kind
  25511. * - BABYLON.VertexBuffer.UV6Kind
  25512. * - BABYLON.VertexBuffer.ColorKind
  25513. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25514. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25515. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25516. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25517. *
  25518. * Returns the Mesh.
  25519. */
  25520. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25521. if (updatable === void 0) { updatable = false; }
  25522. if (!this._geometry) {
  25523. var vertexData = new BABYLON.VertexData();
  25524. vertexData.set(data, kind);
  25525. var scene = this.getScene();
  25526. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25527. }
  25528. else {
  25529. this._geometry.setVerticesData(kind, data, updatable, stride);
  25530. }
  25531. return this;
  25532. };
  25533. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25534. if (updatable === void 0) { updatable = true; }
  25535. var vb = this.getVertexBuffer(kind);
  25536. if (!vb || vb.isUpdatable() === updatable) {
  25537. return;
  25538. }
  25539. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25540. };
  25541. /**
  25542. * Sets the mesh VertexBuffer.
  25543. * Returns the Mesh.
  25544. */
  25545. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25546. if (!this._geometry) {
  25547. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25548. }
  25549. this._geometry.setVerticesBuffer(buffer);
  25550. return this;
  25551. };
  25552. /**
  25553. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25554. * If the mesh has no geometry, it is simply returned as it is.
  25555. * The `data` are either a numeric array either a Float32Array.
  25556. * No new underlying VertexBuffer object is created.
  25557. * 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.
  25558. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25559. *
  25560. * Possible `kind` values :
  25561. * - BABYLON.VertexBuffer.PositionKind
  25562. * - BABYLON.VertexBuffer.UVKind
  25563. * - BABYLON.VertexBuffer.UV2Kind
  25564. * - BABYLON.VertexBuffer.UV3Kind
  25565. * - BABYLON.VertexBuffer.UV4Kind
  25566. * - BABYLON.VertexBuffer.UV5Kind
  25567. * - BABYLON.VertexBuffer.UV6Kind
  25568. * - BABYLON.VertexBuffer.ColorKind
  25569. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25570. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25571. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25572. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25573. *
  25574. * Returns the Mesh.
  25575. */
  25576. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25577. if (!this._geometry) {
  25578. return this;
  25579. }
  25580. if (!makeItUnique) {
  25581. this._geometry.updateVerticesData(kind, data, updateExtends);
  25582. }
  25583. else {
  25584. this.makeGeometryUnique();
  25585. this.updateVerticesData(kind, data, updateExtends, false);
  25586. }
  25587. return this;
  25588. };
  25589. /**
  25590. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25591. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25592. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25593. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25594. * Returns the Mesh.
  25595. */
  25596. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25597. if (computeNormals === void 0) { computeNormals = true; }
  25598. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25599. if (!positions) {
  25600. return this;
  25601. }
  25602. positionFunction(positions);
  25603. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25604. if (computeNormals) {
  25605. var indices = this.getIndices();
  25606. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25607. if (!normals) {
  25608. return this;
  25609. }
  25610. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25611. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25612. }
  25613. return this;
  25614. };
  25615. /**
  25616. * Creates a un-shared specific occurence of the geometry for the mesh.
  25617. * Returns the Mesh.
  25618. */
  25619. Mesh.prototype.makeGeometryUnique = function () {
  25620. if (!this._geometry) {
  25621. return this;
  25622. }
  25623. var oldGeometry = this._geometry;
  25624. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25625. oldGeometry.releaseForMesh(this, true);
  25626. geometry.applyToMesh(this);
  25627. return this;
  25628. };
  25629. /**
  25630. * Sets the mesh indices.
  25631. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25632. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25633. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25634. * This method creates a new index buffer each call.
  25635. * Returns the Mesh.
  25636. */
  25637. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25638. if (totalVertices === void 0) { totalVertices = null; }
  25639. if (updatable === void 0) { updatable = false; }
  25640. if (!this._geometry) {
  25641. var vertexData = new BABYLON.VertexData();
  25642. vertexData.indices = indices;
  25643. var scene = this.getScene();
  25644. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25645. }
  25646. else {
  25647. this._geometry.setIndices(indices, totalVertices, updatable);
  25648. }
  25649. return this;
  25650. };
  25651. /**
  25652. * Update the current index buffer
  25653. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25654. * Returns the Mesh.
  25655. */
  25656. Mesh.prototype.updateIndices = function (indices, offset) {
  25657. if (!this._geometry) {
  25658. return this;
  25659. }
  25660. this._geometry.updateIndices(indices, offset);
  25661. return this;
  25662. };
  25663. /**
  25664. * Invert the geometry to move from a right handed system to a left handed one.
  25665. * Returns the Mesh.
  25666. */
  25667. Mesh.prototype.toLeftHanded = function () {
  25668. if (!this._geometry) {
  25669. return this;
  25670. }
  25671. this._geometry.toLeftHanded();
  25672. return this;
  25673. };
  25674. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25675. if (!this._geometry) {
  25676. return this;
  25677. }
  25678. var engine = this.getScene().getEngine();
  25679. // Wireframe
  25680. var indexToBind;
  25681. if (this._unIndexed) {
  25682. indexToBind = null;
  25683. }
  25684. else {
  25685. switch (fillMode) {
  25686. case BABYLON.Material.PointFillMode:
  25687. indexToBind = null;
  25688. break;
  25689. case BABYLON.Material.WireFrameFillMode:
  25690. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25691. break;
  25692. default:
  25693. case BABYLON.Material.TriangleFillMode:
  25694. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25695. break;
  25696. }
  25697. }
  25698. // VBOs
  25699. this._geometry._bind(effect, indexToBind);
  25700. return this;
  25701. };
  25702. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25703. if (alternate === void 0) { alternate = false; }
  25704. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25705. return this;
  25706. }
  25707. this.onBeforeDrawObservable.notifyObservers(this);
  25708. var scene = this.getScene();
  25709. var engine = scene.getEngine();
  25710. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25711. // or triangles as points
  25712. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25713. }
  25714. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25715. // Triangles as wireframe
  25716. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25717. }
  25718. else {
  25719. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25720. }
  25721. if (scene._isAlternateRenderingEnabled && !alternate) {
  25722. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25723. if (!effect || !scene.activeCamera) {
  25724. return this;
  25725. }
  25726. scene._switchToAlternateCameraConfiguration(true);
  25727. this._effectiveMaterial.bindView(effect);
  25728. this._effectiveMaterial.bindViewProjection(effect);
  25729. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25730. this._draw(subMesh, fillMode, instancesCount, true);
  25731. engine.setViewport(scene.activeCamera.viewport);
  25732. scene._switchToAlternateCameraConfiguration(false);
  25733. this._effectiveMaterial.bindView(effect);
  25734. this._effectiveMaterial.bindViewProjection(effect);
  25735. }
  25736. return this;
  25737. };
  25738. /**
  25739. * Registers for this mesh a javascript function called just before the rendering process.
  25740. * This function is passed the current mesh.
  25741. * Return the Mesh.
  25742. */
  25743. Mesh.prototype.registerBeforeRender = function (func) {
  25744. this.onBeforeRenderObservable.add(func);
  25745. return this;
  25746. };
  25747. /**
  25748. * Disposes a previously registered javascript function called before the rendering.
  25749. * This function is passed the current mesh.
  25750. * Returns the Mesh.
  25751. */
  25752. Mesh.prototype.unregisterBeforeRender = function (func) {
  25753. this.onBeforeRenderObservable.removeCallback(func);
  25754. return this;
  25755. };
  25756. /**
  25757. * Registers for this mesh a javascript function called just after the rendering is complete.
  25758. * This function is passed the current mesh.
  25759. * Returns the Mesh.
  25760. */
  25761. Mesh.prototype.registerAfterRender = function (func) {
  25762. this.onAfterRenderObservable.add(func);
  25763. return this;
  25764. };
  25765. /**
  25766. * Disposes a previously registered javascript function called after the rendering.
  25767. * This function is passed the current mesh.
  25768. * Return the Mesh.
  25769. */
  25770. Mesh.prototype.unregisterAfterRender = function (func) {
  25771. this.onAfterRenderObservable.removeCallback(func);
  25772. return this;
  25773. };
  25774. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25775. var scene = this.getScene();
  25776. this._batchCache.mustReturn = false;
  25777. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25778. this._batchCache.visibleInstances[subMeshId] = null;
  25779. if (this._visibleInstances) {
  25780. var currentRenderId = scene.getRenderId();
  25781. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25782. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25783. var selfRenderId = this._renderId;
  25784. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25785. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25786. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25787. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25788. }
  25789. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25790. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25791. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25792. this._batchCache.mustReturn = true;
  25793. return this._batchCache;
  25794. }
  25795. if (currentRenderId !== selfRenderId) {
  25796. this._batchCache.renderSelf[subMeshId] = false;
  25797. }
  25798. }
  25799. this._renderIdForInstances[subMeshId] = currentRenderId;
  25800. }
  25801. return this._batchCache;
  25802. };
  25803. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25804. var visibleInstances = batch.visibleInstances[subMesh._id];
  25805. if (!visibleInstances) {
  25806. return this;
  25807. }
  25808. var matricesCount = visibleInstances.length + 1;
  25809. var bufferSize = matricesCount * 16 * 4;
  25810. var currentInstancesBufferSize = this._instancesBufferSize;
  25811. var instancesBuffer = this._instancesBuffer;
  25812. while (this._instancesBufferSize < bufferSize) {
  25813. this._instancesBufferSize *= 2;
  25814. }
  25815. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25816. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25817. }
  25818. var offset = 0;
  25819. var instancesCount = 0;
  25820. var world = this.getWorldMatrix();
  25821. if (batch.renderSelf[subMesh._id]) {
  25822. world.copyToArray(this._instancesData, offset);
  25823. offset += 16;
  25824. instancesCount++;
  25825. }
  25826. if (visibleInstances) {
  25827. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25828. var instance = visibleInstances[instanceIndex];
  25829. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25830. offset += 16;
  25831. instancesCount++;
  25832. }
  25833. }
  25834. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25835. if (instancesBuffer) {
  25836. instancesBuffer.dispose();
  25837. }
  25838. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25839. this._instancesBuffer = instancesBuffer;
  25840. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25841. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25842. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25843. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25844. }
  25845. else {
  25846. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25847. }
  25848. this._bind(subMesh, effect, fillMode);
  25849. this._draw(subMesh, fillMode, instancesCount);
  25850. engine.unbindInstanceAttributes();
  25851. return this;
  25852. };
  25853. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25854. var scene = this.getScene();
  25855. var engine = scene.getEngine();
  25856. if (hardwareInstancedRendering) {
  25857. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25858. }
  25859. else {
  25860. if (batch.renderSelf[subMesh._id]) {
  25861. // Draw
  25862. if (onBeforeDraw) {
  25863. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25864. }
  25865. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25866. }
  25867. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25868. if (visibleInstancesForSubMesh) {
  25869. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25870. var instance = visibleInstancesForSubMesh[instanceIndex];
  25871. // World
  25872. var world = instance.getWorldMatrix();
  25873. if (onBeforeDraw) {
  25874. onBeforeDraw(true, world, effectiveMaterial);
  25875. }
  25876. // Draw
  25877. this._draw(subMesh, fillMode);
  25878. }
  25879. }
  25880. }
  25881. return this;
  25882. };
  25883. /**
  25884. * Triggers the draw call for the mesh.
  25885. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25886. * Returns the Mesh.
  25887. */
  25888. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25889. this.checkOcclusionQuery();
  25890. if (this._isOccluded) {
  25891. return this;
  25892. }
  25893. var scene = this.getScene();
  25894. // Managing instances
  25895. var batch = this._getInstancesRenderList(subMesh._id);
  25896. if (batch.mustReturn) {
  25897. return this;
  25898. }
  25899. // Checking geometry state
  25900. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25901. return this;
  25902. }
  25903. this.onBeforeRenderObservable.notifyObservers(this);
  25904. var engine = scene.getEngine();
  25905. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25906. // Material
  25907. var material = subMesh.getMaterial();
  25908. if (!material) {
  25909. return this;
  25910. }
  25911. this._effectiveMaterial = material;
  25912. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25913. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25914. return this;
  25915. }
  25916. }
  25917. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25918. return this;
  25919. }
  25920. // Alpha mode
  25921. if (enableAlphaMode) {
  25922. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25923. }
  25924. // Outline - step 1
  25925. var savedDepthWrite = engine.getDepthWrite();
  25926. if (this.renderOutline) {
  25927. engine.setDepthWrite(false);
  25928. scene.getOutlineRenderer().render(subMesh, batch);
  25929. engine.setDepthWrite(savedDepthWrite);
  25930. }
  25931. var effect;
  25932. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25933. effect = subMesh.effect;
  25934. }
  25935. else {
  25936. effect = this._effectiveMaterial.getEffect();
  25937. }
  25938. if (!effect) {
  25939. return this;
  25940. }
  25941. var sideOrientation = this.overrideMaterialSideOrientation;
  25942. if (sideOrientation == null) {
  25943. sideOrientation = this._effectiveMaterial.sideOrientation;
  25944. if (this._getWorldMatrixDeterminant() < 0) {
  25945. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25946. }
  25947. }
  25948. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25949. if (this._effectiveMaterial.forceDepthWrite) {
  25950. engine.setDepthWrite(true);
  25951. }
  25952. // Bind
  25953. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25954. if (!hardwareInstancedRendering) {
  25955. this._bind(subMesh, effect, fillMode);
  25956. }
  25957. var world = this.getWorldMatrix();
  25958. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25959. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25960. }
  25961. else {
  25962. this._effectiveMaterial.bind(world, this);
  25963. }
  25964. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25965. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25966. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25967. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25968. }
  25969. // Draw
  25970. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25971. // Unbind
  25972. this._effectiveMaterial.unbind();
  25973. // Outline - step 2
  25974. if (this.renderOutline && savedDepthWrite) {
  25975. engine.setDepthWrite(true);
  25976. engine.setColorWrite(false);
  25977. scene.getOutlineRenderer().render(subMesh, batch);
  25978. engine.setColorWrite(true);
  25979. }
  25980. // Overlay
  25981. if (this.renderOverlay) {
  25982. var currentMode = engine.getAlphaMode();
  25983. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25984. scene.getOutlineRenderer().render(subMesh, batch, true);
  25985. engine.setAlphaMode(currentMode);
  25986. }
  25987. this.onAfterRenderObservable.notifyObservers(this);
  25988. return this;
  25989. };
  25990. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25991. if (isInstance && effectiveMaterial) {
  25992. effectiveMaterial.bindOnlyWorldMatrix(world);
  25993. }
  25994. };
  25995. /**
  25996. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25997. */
  25998. Mesh.prototype.getEmittedParticleSystems = function () {
  25999. var results = new Array();
  26000. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26001. var particleSystem = this.getScene().particleSystems[index];
  26002. if (particleSystem.emitter === this) {
  26003. results.push(particleSystem);
  26004. }
  26005. }
  26006. return results;
  26007. };
  26008. /**
  26009. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26010. */
  26011. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26012. var results = new Array();
  26013. var descendants = this.getDescendants();
  26014. descendants.push(this);
  26015. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26016. var particleSystem = this.getScene().particleSystems[index];
  26017. var emitter = particleSystem.emitter;
  26018. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26019. results.push(particleSystem);
  26020. }
  26021. }
  26022. return results;
  26023. };
  26024. Mesh.prototype._checkDelayState = function () {
  26025. var scene = this.getScene();
  26026. if (this._geometry) {
  26027. this._geometry.load(scene);
  26028. }
  26029. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26030. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26031. this._queueLoad(scene);
  26032. }
  26033. return this;
  26034. };
  26035. Mesh.prototype._queueLoad = function (scene) {
  26036. var _this = this;
  26037. scene._addPendingData(this);
  26038. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26039. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26040. if (data instanceof ArrayBuffer) {
  26041. _this._delayLoadingFunction(data, _this);
  26042. }
  26043. else {
  26044. _this._delayLoadingFunction(JSON.parse(data), _this);
  26045. }
  26046. _this.instances.forEach(function (instance) {
  26047. instance._syncSubMeshes();
  26048. });
  26049. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26050. scene._removePendingData(_this);
  26051. }, function () { }, scene.database, getBinaryData);
  26052. return this;
  26053. };
  26054. /**
  26055. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26056. */
  26057. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26058. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26059. return false;
  26060. }
  26061. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26062. return false;
  26063. }
  26064. this._checkDelayState();
  26065. return true;
  26066. };
  26067. /**
  26068. * Sets the mesh material by the material or multiMaterial `id` property.
  26069. * The material `id` is a string identifying the material or the multiMaterial.
  26070. * This method returns the Mesh.
  26071. */
  26072. Mesh.prototype.setMaterialByID = function (id) {
  26073. var materials = this.getScene().materials;
  26074. var index;
  26075. for (index = materials.length - 1; index > -1; index--) {
  26076. if (materials[index].id === id) {
  26077. this.material = materials[index];
  26078. return this;
  26079. }
  26080. }
  26081. // Multi
  26082. var multiMaterials = this.getScene().multiMaterials;
  26083. for (index = multiMaterials.length - 1; index > -1; index--) {
  26084. if (multiMaterials[index].id === id) {
  26085. this.material = multiMaterials[index];
  26086. return this;
  26087. }
  26088. }
  26089. return this;
  26090. };
  26091. /**
  26092. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26093. */
  26094. Mesh.prototype.getAnimatables = function () {
  26095. var results = new Array();
  26096. if (this.material) {
  26097. results.push(this.material);
  26098. }
  26099. if (this.skeleton) {
  26100. results.push(this.skeleton);
  26101. }
  26102. return results;
  26103. };
  26104. /**
  26105. * Modifies the mesh geometry according to the passed transformation matrix.
  26106. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26107. * The mesh normals are modified accordingly the same transformation.
  26108. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26109. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26110. * Returns the Mesh.
  26111. */
  26112. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26113. // Position
  26114. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26115. return this;
  26116. }
  26117. var submeshes = this.subMeshes.splice(0);
  26118. this._resetPointsArrayCache();
  26119. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26120. var temp = new Array();
  26121. var index;
  26122. for (index = 0; index < data.length; index += 3) {
  26123. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26124. }
  26125. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26126. // Normals
  26127. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26128. return this;
  26129. }
  26130. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26131. temp = [];
  26132. for (index = 0; index < data.length; index += 3) {
  26133. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26134. }
  26135. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26136. // flip faces?
  26137. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26138. this.flipFaces();
  26139. }
  26140. // Restore submeshes
  26141. this.releaseSubMeshes();
  26142. this.subMeshes = submeshes;
  26143. return this;
  26144. };
  26145. /**
  26146. * Modifies the mesh geometry according to its own current World Matrix.
  26147. * The mesh World Matrix is then reset.
  26148. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26149. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26150. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26151. * Returns the Mesh.
  26152. */
  26153. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26154. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26155. this.scaling.copyFromFloats(1, 1, 1);
  26156. this.position.copyFromFloats(0, 0, 0);
  26157. this.rotation.copyFromFloats(0, 0, 0);
  26158. //only if quaternion is already set
  26159. if (this.rotationQuaternion) {
  26160. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26161. }
  26162. this._worldMatrix = BABYLON.Matrix.Identity();
  26163. return this;
  26164. };
  26165. Object.defineProperty(Mesh.prototype, "_positions", {
  26166. // Cache
  26167. get: function () {
  26168. if (this._geometry) {
  26169. return this._geometry._positions;
  26170. }
  26171. return null;
  26172. },
  26173. enumerable: true,
  26174. configurable: true
  26175. });
  26176. Mesh.prototype._resetPointsArrayCache = function () {
  26177. if (this._geometry) {
  26178. this._geometry._resetPointsArrayCache();
  26179. }
  26180. return this;
  26181. };
  26182. Mesh.prototype._generatePointsArray = function () {
  26183. if (this._geometry) {
  26184. return this._geometry._generatePointsArray();
  26185. }
  26186. return false;
  26187. };
  26188. /**
  26189. * Returns a new Mesh object generated from the current mesh properties.
  26190. * This method must not get confused with createInstance().
  26191. * The parameter `name` is a string, the name given to the new mesh.
  26192. * The optional parameter `newParent` can be any Node object (default `null`).
  26193. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26194. * 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.
  26195. */
  26196. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26197. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26198. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26199. };
  26200. /**
  26201. * Disposes the Mesh.
  26202. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26203. * Returns nothing.
  26204. */
  26205. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26206. var _this = this;
  26207. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26208. this.morphTargetManager = null;
  26209. if (this._geometry) {
  26210. this._geometry.releaseForMesh(this, true);
  26211. }
  26212. // Sources
  26213. var meshes = this.getScene().meshes;
  26214. meshes.forEach(function (abstractMesh) {
  26215. var mesh = abstractMesh;
  26216. if (mesh._source && mesh._source === _this) {
  26217. mesh._source = null;
  26218. }
  26219. });
  26220. this._source = null;
  26221. // Instances
  26222. if (this._instancesBuffer) {
  26223. this._instancesBuffer.dispose();
  26224. this._instancesBuffer = null;
  26225. }
  26226. while (this.instances.length) {
  26227. this.instances[0].dispose();
  26228. }
  26229. // Highlight layers.
  26230. var highlightLayers = this.getScene().highlightLayers;
  26231. for (var i = 0; i < highlightLayers.length; i++) {
  26232. var highlightLayer = highlightLayers[i];
  26233. if (highlightLayer) {
  26234. highlightLayer.removeMesh(this);
  26235. highlightLayer.removeExcludedMesh(this);
  26236. }
  26237. }
  26238. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26239. };
  26240. /**
  26241. * Modifies the mesh geometry according to a displacement map.
  26242. * 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.
  26243. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26244. * This method returns nothing.
  26245. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26246. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26247. * 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.
  26248. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26249. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26250. *
  26251. * Returns the Mesh.
  26252. */
  26253. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26254. var _this = this;
  26255. var scene = this.getScene();
  26256. var onload = function (img) {
  26257. // Getting height map data
  26258. var canvas = document.createElement("canvas");
  26259. var context = canvas.getContext("2d");
  26260. var heightMapWidth = img.width;
  26261. var heightMapHeight = img.height;
  26262. canvas.width = heightMapWidth;
  26263. canvas.height = heightMapHeight;
  26264. context.drawImage(img, 0, 0);
  26265. // Create VertexData from map data
  26266. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26267. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26268. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26269. //execute success callback, if set
  26270. if (onSuccess) {
  26271. onSuccess(_this);
  26272. }
  26273. };
  26274. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26275. return this;
  26276. };
  26277. /**
  26278. * Modifies the mesh geometry according to a displacementMap buffer.
  26279. * 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.
  26280. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26281. * This method returns nothing.
  26282. * 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.
  26283. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26284. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26285. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26286. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26287. *
  26288. * Returns the Mesh.
  26289. */
  26290. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26291. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26292. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26293. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26294. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26295. return this;
  26296. }
  26297. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26298. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26299. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26300. var position = BABYLON.Vector3.Zero();
  26301. var normal = BABYLON.Vector3.Zero();
  26302. var uv = BABYLON.Vector2.Zero();
  26303. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26304. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26305. for (var index = 0; index < positions.length; index += 3) {
  26306. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26307. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26308. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26309. // Compute height
  26310. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26311. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26312. var pos = (u + v * heightMapWidth) * 4;
  26313. var r = buffer[pos] / 255.0;
  26314. var g = buffer[pos + 1] / 255.0;
  26315. var b = buffer[pos + 2] / 255.0;
  26316. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26317. normal.normalize();
  26318. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26319. position = position.add(normal);
  26320. position.toArray(positions, index);
  26321. }
  26322. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26323. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26324. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26325. return this;
  26326. };
  26327. /**
  26328. * Modify the mesh to get a flat shading rendering.
  26329. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26330. * This method returns the Mesh.
  26331. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26332. */
  26333. Mesh.prototype.convertToFlatShadedMesh = function () {
  26334. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26335. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26336. var kinds = this.getVerticesDataKinds();
  26337. var vbs = {};
  26338. var data = {};
  26339. var newdata = {};
  26340. var updatableNormals = false;
  26341. var kindIndex;
  26342. var kind;
  26343. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26344. kind = kinds[kindIndex];
  26345. var vertexBuffer = this.getVertexBuffer(kind);
  26346. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26347. updatableNormals = vertexBuffer.isUpdatable();
  26348. kinds.splice(kindIndex, 1);
  26349. kindIndex--;
  26350. continue;
  26351. }
  26352. vbs[kind] = vertexBuffer;
  26353. data[kind] = vbs[kind].getData();
  26354. newdata[kind] = [];
  26355. }
  26356. // Save previous submeshes
  26357. var previousSubmeshes = this.subMeshes.slice(0);
  26358. var indices = this.getIndices();
  26359. var totalIndices = this.getTotalIndices();
  26360. // Generating unique vertices per face
  26361. var index;
  26362. for (index = 0; index < totalIndices; index++) {
  26363. var vertexIndex = indices[index];
  26364. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26365. kind = kinds[kindIndex];
  26366. var stride = vbs[kind].getStrideSize();
  26367. for (var offset = 0; offset < stride; offset++) {
  26368. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26369. }
  26370. }
  26371. }
  26372. // Updating faces & normal
  26373. var normals = [];
  26374. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26375. for (index = 0; index < totalIndices; index += 3) {
  26376. indices[index] = index;
  26377. indices[index + 1] = index + 1;
  26378. indices[index + 2] = index + 2;
  26379. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26380. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26381. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26382. var p1p2 = p1.subtract(p2);
  26383. var p3p2 = p3.subtract(p2);
  26384. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26385. // Store same normals for every vertex
  26386. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26387. normals.push(normal.x);
  26388. normals.push(normal.y);
  26389. normals.push(normal.z);
  26390. }
  26391. }
  26392. this.setIndices(indices);
  26393. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26394. // Updating vertex buffers
  26395. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26396. kind = kinds[kindIndex];
  26397. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26398. }
  26399. // Updating submeshes
  26400. this.releaseSubMeshes();
  26401. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26402. var previousOne = previousSubmeshes[submeshIndex];
  26403. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26404. }
  26405. this.synchronizeInstances();
  26406. return this;
  26407. };
  26408. /**
  26409. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26410. * In other words, more vertices, no more indices and a single bigger VBO.
  26411. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26412. * Returns the Mesh.
  26413. */
  26414. Mesh.prototype.convertToUnIndexedMesh = function () {
  26415. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26416. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26417. var kinds = this.getVerticesDataKinds();
  26418. var vbs = {};
  26419. var data = {};
  26420. var newdata = {};
  26421. var kindIndex;
  26422. var kind;
  26423. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26424. kind = kinds[kindIndex];
  26425. var vertexBuffer = this.getVertexBuffer(kind);
  26426. vbs[kind] = vertexBuffer;
  26427. data[kind] = vbs[kind].getData();
  26428. newdata[kind] = [];
  26429. }
  26430. // Save previous submeshes
  26431. var previousSubmeshes = this.subMeshes.slice(0);
  26432. var indices = this.getIndices();
  26433. var totalIndices = this.getTotalIndices();
  26434. // Generating unique vertices per face
  26435. var index;
  26436. for (index = 0; index < totalIndices; index++) {
  26437. var vertexIndex = indices[index];
  26438. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26439. kind = kinds[kindIndex];
  26440. var stride = vbs[kind].getStrideSize();
  26441. for (var offset = 0; offset < stride; offset++) {
  26442. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26443. }
  26444. }
  26445. }
  26446. // Updating indices
  26447. for (index = 0; index < totalIndices; index += 3) {
  26448. indices[index] = index;
  26449. indices[index + 1] = index + 1;
  26450. indices[index + 2] = index + 2;
  26451. }
  26452. this.setIndices(indices);
  26453. // Updating vertex buffers
  26454. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26455. kind = kinds[kindIndex];
  26456. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26457. }
  26458. // Updating submeshes
  26459. this.releaseSubMeshes();
  26460. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26461. var previousOne = previousSubmeshes[submeshIndex];
  26462. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26463. }
  26464. this._unIndexed = true;
  26465. this.synchronizeInstances();
  26466. return this;
  26467. };
  26468. /**
  26469. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26470. * This method returns the Mesh.
  26471. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26472. */
  26473. Mesh.prototype.flipFaces = function (flipNormals) {
  26474. if (flipNormals === void 0) { flipNormals = false; }
  26475. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26476. var i;
  26477. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26478. for (i = 0; i < vertex_data.normals.length; i++) {
  26479. vertex_data.normals[i] *= -1;
  26480. }
  26481. }
  26482. if (vertex_data.indices) {
  26483. var temp;
  26484. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26485. // reassign indices
  26486. temp = vertex_data.indices[i + 1];
  26487. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26488. vertex_data.indices[i + 2] = temp;
  26489. }
  26490. }
  26491. vertex_data.applyToMesh(this);
  26492. return this;
  26493. };
  26494. // Instances
  26495. /**
  26496. * Creates a new InstancedMesh object from the mesh model.
  26497. * An instance shares the same properties and the same material than its model.
  26498. * Only these properties of each instance can then be set individually :
  26499. * - position
  26500. * - rotation
  26501. * - rotationQuaternion
  26502. * - setPivotMatrix
  26503. * - scaling
  26504. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26505. * Warning : this method is not supported for Line mesh and LineSystem
  26506. */
  26507. Mesh.prototype.createInstance = function (name) {
  26508. return new BABYLON.InstancedMesh(name, this);
  26509. };
  26510. /**
  26511. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26512. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26513. * This method returns the Mesh.
  26514. */
  26515. Mesh.prototype.synchronizeInstances = function () {
  26516. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26517. var instance = this.instances[instanceIndex];
  26518. instance._syncSubMeshes();
  26519. }
  26520. return this;
  26521. };
  26522. /**
  26523. * Simplify the mesh according to the given array of settings.
  26524. * Function will return immediately and will simplify async. It returns the Mesh.
  26525. * @param settings a collection of simplification settings.
  26526. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26527. * @param type the type of simplification to run.
  26528. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26529. */
  26530. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26531. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26532. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26533. this.getScene().simplificationQueue.addTask({
  26534. settings: settings,
  26535. parallelProcessing: parallelProcessing,
  26536. mesh: this,
  26537. simplificationType: simplificationType,
  26538. successCallback: successCallback
  26539. });
  26540. return this;
  26541. };
  26542. /**
  26543. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26544. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26545. * This should be used together with the simplification to avoid disappearing triangles.
  26546. * Returns the Mesh.
  26547. * @param successCallback an optional success callback to be called after the optimization finished.
  26548. */
  26549. Mesh.prototype.optimizeIndices = function (successCallback) {
  26550. var _this = this;
  26551. var indices = this.getIndices();
  26552. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26553. if (!positions || !indices) {
  26554. return this;
  26555. }
  26556. var vectorPositions = new Array();
  26557. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26558. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26559. }
  26560. var dupes = new Array();
  26561. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26562. var realPos = vectorPositions.length - 1 - iteration;
  26563. var testedPosition = vectorPositions[realPos];
  26564. for (var j = 0; j < realPos; ++j) {
  26565. var againstPosition = vectorPositions[j];
  26566. if (testedPosition.equals(againstPosition)) {
  26567. dupes[realPos] = j;
  26568. break;
  26569. }
  26570. }
  26571. }, function () {
  26572. for (var i = 0; i < indices.length; ++i) {
  26573. indices[i] = dupes[indices[i]] || indices[i];
  26574. }
  26575. //indices are now reordered
  26576. var originalSubMeshes = _this.subMeshes.slice(0);
  26577. _this.setIndices(indices);
  26578. _this.subMeshes = originalSubMeshes;
  26579. if (successCallback) {
  26580. successCallback(_this);
  26581. }
  26582. });
  26583. return this;
  26584. };
  26585. Mesh.prototype.serialize = function (serializationObject) {
  26586. serializationObject.name = this.name;
  26587. serializationObject.id = this.id;
  26588. serializationObject.type = this.getClassName();
  26589. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26590. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26591. }
  26592. serializationObject.position = this.position.asArray();
  26593. if (this.rotationQuaternion) {
  26594. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26595. }
  26596. else if (this.rotation) {
  26597. serializationObject.rotation = this.rotation.asArray();
  26598. }
  26599. serializationObject.scaling = this.scaling.asArray();
  26600. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26601. serializationObject.isEnabled = this.isEnabled(false);
  26602. serializationObject.isVisible = this.isVisible;
  26603. serializationObject.infiniteDistance = this.infiniteDistance;
  26604. serializationObject.pickable = this.isPickable;
  26605. serializationObject.receiveShadows = this.receiveShadows;
  26606. serializationObject.billboardMode = this.billboardMode;
  26607. serializationObject.visibility = this.visibility;
  26608. serializationObject.checkCollisions = this.checkCollisions;
  26609. serializationObject.isBlocker = this.isBlocker;
  26610. // Parent
  26611. if (this.parent) {
  26612. serializationObject.parentId = this.parent.id;
  26613. }
  26614. // Geometry
  26615. serializationObject.isUnIndexed = this.isUnIndexed;
  26616. var geometry = this._geometry;
  26617. if (geometry) {
  26618. var geometryId = geometry.id;
  26619. serializationObject.geometryId = geometryId;
  26620. // SubMeshes
  26621. serializationObject.subMeshes = [];
  26622. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26623. var subMesh = this.subMeshes[subIndex];
  26624. serializationObject.subMeshes.push({
  26625. materialIndex: subMesh.materialIndex,
  26626. verticesStart: subMesh.verticesStart,
  26627. verticesCount: subMesh.verticesCount,
  26628. indexStart: subMesh.indexStart,
  26629. indexCount: subMesh.indexCount
  26630. });
  26631. }
  26632. }
  26633. // Material
  26634. if (this.material) {
  26635. serializationObject.materialId = this.material.id;
  26636. }
  26637. else {
  26638. this.material = null;
  26639. }
  26640. // Morph targets
  26641. if (this.morphTargetManager) {
  26642. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26643. }
  26644. // Skeleton
  26645. if (this.skeleton) {
  26646. serializationObject.skeletonId = this.skeleton.id;
  26647. }
  26648. // Physics
  26649. //TODO implement correct serialization for physics impostors.
  26650. var impostor = this.getPhysicsImpostor();
  26651. if (impostor) {
  26652. serializationObject.physicsMass = impostor.getParam("mass");
  26653. serializationObject.physicsFriction = impostor.getParam("friction");
  26654. serializationObject.physicsRestitution = impostor.getParam("mass");
  26655. serializationObject.physicsImpostor = impostor.type;
  26656. }
  26657. // Metadata
  26658. if (this.metadata) {
  26659. serializationObject.metadata = this.metadata;
  26660. }
  26661. // Instances
  26662. serializationObject.instances = [];
  26663. for (var index = 0; index < this.instances.length; index++) {
  26664. var instance = this.instances[index];
  26665. var serializationInstance = {
  26666. name: instance.name,
  26667. id: instance.id,
  26668. position: instance.position.asArray(),
  26669. scaling: instance.scaling.asArray()
  26670. };
  26671. if (instance.rotationQuaternion) {
  26672. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26673. }
  26674. else if (instance.rotation) {
  26675. serializationInstance.rotation = instance.rotation.asArray();
  26676. }
  26677. serializationObject.instances.push(serializationInstance);
  26678. // Animations
  26679. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26680. serializationInstance.ranges = instance.serializeAnimationRanges();
  26681. }
  26682. //
  26683. // Animations
  26684. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26685. serializationObject.ranges = this.serializeAnimationRanges();
  26686. // Layer mask
  26687. serializationObject.layerMask = this.layerMask;
  26688. // Alpha
  26689. serializationObject.alphaIndex = this.alphaIndex;
  26690. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26691. // Overlay
  26692. serializationObject.overlayAlpha = this.overlayAlpha;
  26693. serializationObject.overlayColor = this.overlayColor.asArray();
  26694. serializationObject.renderOverlay = this.renderOverlay;
  26695. // Fog
  26696. serializationObject.applyFog = this.applyFog;
  26697. // Action Manager
  26698. if (this.actionManager) {
  26699. serializationObject.actions = this.actionManager.serialize(this.name);
  26700. }
  26701. };
  26702. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26703. if (!this.geometry) {
  26704. return;
  26705. }
  26706. this._markSubMeshesAsAttributesDirty();
  26707. var morphTargetManager = this._morphTargetManager;
  26708. if (morphTargetManager && morphTargetManager.vertexCount) {
  26709. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26710. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26711. this.morphTargetManager = null;
  26712. return;
  26713. }
  26714. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26715. var morphTarget = morphTargetManager.getActiveTarget(index);
  26716. var positions = morphTarget.getPositions();
  26717. if (!positions) {
  26718. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26719. return;
  26720. }
  26721. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26722. var normals = morphTarget.getNormals();
  26723. if (normals) {
  26724. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26725. }
  26726. var tangents = morphTarget.getTangents();
  26727. if (tangents) {
  26728. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26729. }
  26730. }
  26731. }
  26732. else {
  26733. var index = 0;
  26734. // Positions
  26735. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26736. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26737. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26738. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26739. }
  26740. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26741. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26742. }
  26743. index++;
  26744. }
  26745. }
  26746. };
  26747. // Statics
  26748. /**
  26749. * Returns a new Mesh object parsed from the source provided.
  26750. * The parameter `parsedMesh` is the source.
  26751. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26752. */
  26753. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26754. var mesh;
  26755. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26756. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26757. }
  26758. else {
  26759. mesh = new Mesh(parsedMesh.name, scene);
  26760. }
  26761. mesh.id = parsedMesh.id;
  26762. if (BABYLON.Tags) {
  26763. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26764. }
  26765. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26766. if (parsedMesh.metadata !== undefined) {
  26767. mesh.metadata = parsedMesh.metadata;
  26768. }
  26769. if (parsedMesh.rotationQuaternion) {
  26770. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26771. }
  26772. else if (parsedMesh.rotation) {
  26773. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26774. }
  26775. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26776. if (parsedMesh.localMatrix) {
  26777. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26778. }
  26779. else if (parsedMesh.pivotMatrix) {
  26780. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26781. }
  26782. mesh.setEnabled(parsedMesh.isEnabled);
  26783. mesh.isVisible = parsedMesh.isVisible;
  26784. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26785. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26786. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26787. if (parsedMesh.applyFog !== undefined) {
  26788. mesh.applyFog = parsedMesh.applyFog;
  26789. }
  26790. if (parsedMesh.pickable !== undefined) {
  26791. mesh.isPickable = parsedMesh.pickable;
  26792. }
  26793. if (parsedMesh.alphaIndex !== undefined) {
  26794. mesh.alphaIndex = parsedMesh.alphaIndex;
  26795. }
  26796. mesh.receiveShadows = parsedMesh.receiveShadows;
  26797. mesh.billboardMode = parsedMesh.billboardMode;
  26798. if (parsedMesh.visibility !== undefined) {
  26799. mesh.visibility = parsedMesh.visibility;
  26800. }
  26801. mesh.checkCollisions = parsedMesh.checkCollisions;
  26802. if (parsedMesh.isBlocker !== undefined) {
  26803. mesh.isBlocker = parsedMesh.isBlocker;
  26804. }
  26805. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26806. // freezeWorldMatrix
  26807. if (parsedMesh.freezeWorldMatrix) {
  26808. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26809. }
  26810. // Parent
  26811. if (parsedMesh.parentId) {
  26812. mesh._waitingParentId = parsedMesh.parentId;
  26813. }
  26814. // Actions
  26815. if (parsedMesh.actions !== undefined) {
  26816. mesh._waitingActions = parsedMesh.actions;
  26817. }
  26818. // Overlay
  26819. if (parsedMesh.overlayAlpha !== undefined) {
  26820. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26821. }
  26822. if (parsedMesh.overlayColor !== undefined) {
  26823. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26824. }
  26825. if (parsedMesh.renderOverlay !== undefined) {
  26826. mesh.renderOverlay = parsedMesh.renderOverlay;
  26827. }
  26828. // Geometry
  26829. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26830. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26831. if (parsedMesh.delayLoadingFile) {
  26832. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26833. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26834. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26835. if (parsedMesh._binaryInfo) {
  26836. mesh._binaryInfo = parsedMesh._binaryInfo;
  26837. }
  26838. mesh._delayInfo = [];
  26839. if (parsedMesh.hasUVs) {
  26840. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26841. }
  26842. if (parsedMesh.hasUVs2) {
  26843. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26844. }
  26845. if (parsedMesh.hasUVs3) {
  26846. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26847. }
  26848. if (parsedMesh.hasUVs4) {
  26849. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26850. }
  26851. if (parsedMesh.hasUVs5) {
  26852. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26853. }
  26854. if (parsedMesh.hasUVs6) {
  26855. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26856. }
  26857. if (parsedMesh.hasColors) {
  26858. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26859. }
  26860. if (parsedMesh.hasMatricesIndices) {
  26861. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26862. }
  26863. if (parsedMesh.hasMatricesWeights) {
  26864. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26865. }
  26866. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26867. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26868. mesh._checkDelayState();
  26869. }
  26870. }
  26871. else {
  26872. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26873. }
  26874. // Material
  26875. if (parsedMesh.materialId) {
  26876. mesh.setMaterialByID(parsedMesh.materialId);
  26877. }
  26878. else {
  26879. mesh.material = null;
  26880. }
  26881. // Morph targets
  26882. if (parsedMesh.morphTargetManagerId > -1) {
  26883. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26884. }
  26885. // Skeleton
  26886. if (parsedMesh.skeletonId > -1) {
  26887. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26888. if (parsedMesh.numBoneInfluencers) {
  26889. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26890. }
  26891. }
  26892. // Animations
  26893. if (parsedMesh.animations) {
  26894. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26895. var parsedAnimation = parsedMesh.animations[animationIndex];
  26896. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26897. }
  26898. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26899. }
  26900. if (parsedMesh.autoAnimate) {
  26901. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26902. }
  26903. // Layer Mask
  26904. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26905. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26906. }
  26907. else {
  26908. mesh.layerMask = 0x0FFFFFFF;
  26909. }
  26910. // Physics
  26911. if (parsedMesh.physicsImpostor) {
  26912. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26913. mass: parsedMesh.physicsMass,
  26914. friction: parsedMesh.physicsFriction,
  26915. restitution: parsedMesh.physicsRestitution
  26916. }, scene);
  26917. }
  26918. // Instances
  26919. if (parsedMesh.instances) {
  26920. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26921. var parsedInstance = parsedMesh.instances[index];
  26922. var instance = mesh.createInstance(parsedInstance.name);
  26923. if (parsedInstance.id) {
  26924. instance.id = parsedInstance.id;
  26925. }
  26926. if (BABYLON.Tags) {
  26927. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26928. }
  26929. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26930. if (parsedInstance.parentId) {
  26931. instance._waitingParentId = parsedInstance.parentId;
  26932. }
  26933. if (parsedInstance.rotationQuaternion) {
  26934. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26935. }
  26936. else if (parsedInstance.rotation) {
  26937. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26938. }
  26939. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26940. instance.checkCollisions = mesh.checkCollisions;
  26941. if (parsedMesh.animations) {
  26942. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26943. parsedAnimation = parsedMesh.animations[animationIndex];
  26944. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26945. }
  26946. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26947. }
  26948. }
  26949. }
  26950. return mesh;
  26951. };
  26952. /**
  26953. * Creates a ribbon mesh.
  26954. * Please consider using the same method from the MeshBuilder class instead.
  26955. * 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.
  26956. *
  26957. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26958. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26959. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26960. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26961. * 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.
  26962. * 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.
  26963. * 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
  26964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26965. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26967. */
  26968. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26969. if (closeArray === void 0) { closeArray = false; }
  26970. if (updatable === void 0) { updatable = false; }
  26971. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26972. pathArray: pathArray,
  26973. closeArray: closeArray,
  26974. closePath: closePath,
  26975. offset: offset,
  26976. updatable: updatable,
  26977. sideOrientation: sideOrientation,
  26978. instance: instance
  26979. }, scene);
  26980. };
  26981. /**
  26982. * Creates a plane polygonal mesh. By default, this is a disc.
  26983. * Please consider using the same method from the MeshBuilder class instead.
  26984. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26985. * 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.
  26986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26989. */
  26990. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26991. if (scene === void 0) { scene = null; }
  26992. var options = {
  26993. radius: radius,
  26994. tessellation: tessellation,
  26995. sideOrientation: sideOrientation,
  26996. updatable: updatable
  26997. };
  26998. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  26999. };
  27000. /**
  27001. * Creates a box mesh.
  27002. * Please consider using the same method from the MeshBuilder class instead.
  27003. * The parameter `size` sets the size (float) of each box side (default 1).
  27004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27007. */
  27008. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27009. if (scene === void 0) { scene = null; }
  27010. var options = {
  27011. size: size,
  27012. sideOrientation: sideOrientation,
  27013. updatable: updatable
  27014. };
  27015. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27016. };
  27017. /**
  27018. * Creates a sphere mesh.
  27019. * Please consider using the same method from the MeshBuilder class instead.
  27020. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27021. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27023. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27025. */
  27026. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27027. var options = {
  27028. segments: segments,
  27029. diameterX: diameter,
  27030. diameterY: diameter,
  27031. diameterZ: diameter,
  27032. sideOrientation: sideOrientation,
  27033. updatable: updatable
  27034. };
  27035. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27036. };
  27037. /**
  27038. * Creates a cylinder or a cone mesh.
  27039. * Please consider using the same method from the MeshBuilder class instead.
  27040. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27041. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27042. * 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.
  27043. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27044. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27046. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27048. */
  27049. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27050. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27051. if (scene !== undefined) {
  27052. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27053. updatable = scene;
  27054. }
  27055. scene = subdivisions;
  27056. subdivisions = 1;
  27057. }
  27058. var options = {
  27059. height: height,
  27060. diameterTop: diameterTop,
  27061. diameterBottom: diameterBottom,
  27062. tessellation: tessellation,
  27063. subdivisions: subdivisions,
  27064. sideOrientation: sideOrientation,
  27065. updatable: updatable
  27066. };
  27067. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27068. };
  27069. // Torus (Code from SharpDX.org)
  27070. /**
  27071. * Creates a torus mesh.
  27072. * Please consider using the same method from the MeshBuilder class instead.
  27073. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27074. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27075. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27077. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27078. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27079. */
  27080. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27081. var options = {
  27082. diameter: diameter,
  27083. thickness: thickness,
  27084. tessellation: tessellation,
  27085. sideOrientation: sideOrientation,
  27086. updatable: updatable
  27087. };
  27088. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27089. };
  27090. /**
  27091. * Creates a torus knot mesh.
  27092. * Please consider using the same method from the MeshBuilder class instead.
  27093. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27094. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27095. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27096. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27100. */
  27101. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27102. var options = {
  27103. radius: radius,
  27104. tube: tube,
  27105. radialSegments: radialSegments,
  27106. tubularSegments: tubularSegments,
  27107. p: p,
  27108. q: q,
  27109. sideOrientation: sideOrientation,
  27110. updatable: updatable
  27111. };
  27112. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27113. };
  27114. /**
  27115. * Creates a line mesh.
  27116. * Please consider using the same method from the MeshBuilder class instead.
  27117. * 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.
  27118. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27119. * The parameter `points` is an array successive Vector3.
  27120. * 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
  27121. * When updating an instance, remember that only point positions can change, not the number of points.
  27122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27123. */
  27124. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27125. if (scene === void 0) { scene = null; }
  27126. if (updatable === void 0) { updatable = false; }
  27127. if (instance === void 0) { instance = null; }
  27128. var options = {
  27129. points: points,
  27130. updatable: updatable,
  27131. instance: instance
  27132. };
  27133. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27134. };
  27135. /**
  27136. * Creates a dashed line mesh.
  27137. * Please consider using the same method from the MeshBuilder class instead.
  27138. * 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.
  27139. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27140. * The parameter `points` is an array successive Vector3.
  27141. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27142. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27143. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27144. * 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
  27145. * When updating an instance, remember that only point positions can change, not the number of points.
  27146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27147. */
  27148. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27149. if (scene === void 0) { scene = null; }
  27150. var options = {
  27151. points: points,
  27152. dashSize: dashSize,
  27153. gapSize: gapSize,
  27154. dashNb: dashNb,
  27155. updatable: updatable,
  27156. instance: instance
  27157. };
  27158. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27159. };
  27160. /**
  27161. * Creates a polygon mesh.
  27162. * Please consider using the same method from the MeshBuilder class instead.
  27163. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27164. * 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.
  27165. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27167. * Remember you can only change the shape positions, not their number when updating a polygon.
  27168. */
  27169. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27170. var options = {
  27171. shape: shape,
  27172. holes: holes,
  27173. updatable: updatable,
  27174. sideOrientation: sideOrientation
  27175. };
  27176. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27177. };
  27178. /**
  27179. * Creates an extruded polygon mesh, with depth in the Y direction.
  27180. * Please consider using the same method from the MeshBuilder class instead.
  27181. */
  27182. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27183. var options = {
  27184. shape: shape,
  27185. holes: holes,
  27186. depth: depth,
  27187. updatable: updatable,
  27188. sideOrientation: sideOrientation
  27189. };
  27190. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27191. };
  27192. /**
  27193. * Creates an extruded shape mesh.
  27194. * 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.
  27195. * Please consider using the same method from the MeshBuilder class instead.
  27196. *
  27197. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27198. * 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
  27199. * extruded along the Z axis.
  27200. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27201. * 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.
  27202. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27203. * 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
  27204. * 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
  27205. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27209. */
  27210. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27211. if (scene === void 0) { scene = null; }
  27212. var options = {
  27213. shape: shape,
  27214. path: path,
  27215. scale: scale,
  27216. rotation: rotation,
  27217. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27218. sideOrientation: sideOrientation,
  27219. instance: instance,
  27220. updatable: updatable
  27221. };
  27222. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27223. };
  27224. /**
  27225. * Creates an custom extruded shape mesh.
  27226. * 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.
  27227. * Please consider using the same method from the MeshBuilder class instead.
  27228. *
  27229. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27230. * 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
  27231. * extruded along the Z axis.
  27232. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27233. * 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
  27234. * and the distance of this point from the begining of the path :
  27235. * ```javascript
  27236. * var rotationFunction = function(i, distance) {
  27237. * // do things
  27238. * return rotationValue; }
  27239. * ```
  27240. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27241. * 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
  27242. * and the distance of this point from the begining of the path :
  27243. * ```javascript
  27244. * var scaleFunction = function(i, distance) {
  27245. * // do things
  27246. * return scaleValue;}
  27247. * ```
  27248. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27249. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27250. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27251. * 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
  27252. * 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
  27253. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27255. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27257. */
  27258. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27259. var options = {
  27260. shape: shape,
  27261. path: path,
  27262. scaleFunction: scaleFunction,
  27263. rotationFunction: rotationFunction,
  27264. ribbonCloseArray: ribbonCloseArray,
  27265. ribbonClosePath: ribbonClosePath,
  27266. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27267. sideOrientation: sideOrientation,
  27268. instance: instance,
  27269. updatable: updatable
  27270. };
  27271. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27272. };
  27273. /**
  27274. * Creates lathe mesh.
  27275. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27276. * Please consider using the same method from the MeshBuilder class instead.
  27277. * 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
  27278. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27279. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27280. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27284. */
  27285. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27286. var options = {
  27287. shape: shape,
  27288. radius: radius,
  27289. tessellation: tessellation,
  27290. sideOrientation: sideOrientation,
  27291. updatable: updatable
  27292. };
  27293. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27294. };
  27295. /**
  27296. * Creates a plane mesh.
  27297. * Please consider using the same method from the MeshBuilder class instead.
  27298. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27300. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27302. */
  27303. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27304. var options = {
  27305. size: size,
  27306. width: size,
  27307. height: size,
  27308. sideOrientation: sideOrientation,
  27309. updatable: updatable
  27310. };
  27311. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27312. };
  27313. /**
  27314. * Creates a ground mesh.
  27315. * Please consider using the same method from the MeshBuilder class instead.
  27316. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27317. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27319. */
  27320. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27321. var options = {
  27322. width: width,
  27323. height: height,
  27324. subdivisions: subdivisions,
  27325. updatable: updatable
  27326. };
  27327. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27328. };
  27329. /**
  27330. * Creates a tiled ground mesh.
  27331. * Please consider using the same method from the MeshBuilder class instead.
  27332. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27333. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27334. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27335. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27336. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27337. * numbers of subdivisions on the ground width and height of each tile.
  27338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27339. */
  27340. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27341. var options = {
  27342. xmin: xmin,
  27343. zmin: zmin,
  27344. xmax: xmax,
  27345. zmax: zmax,
  27346. subdivisions: subdivisions,
  27347. precision: precision,
  27348. updatable: updatable
  27349. };
  27350. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27351. };
  27352. /**
  27353. * Creates a ground mesh from a height map.
  27354. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27355. * Please consider using the same method from the MeshBuilder class instead.
  27356. * The parameter `url` sets the URL of the height map image resource.
  27357. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27358. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27359. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27360. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27361. * 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).
  27362. * This function is passed the newly built mesh :
  27363. * ```javascript
  27364. * function(mesh) { // do things
  27365. * return; }
  27366. * ```
  27367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27368. */
  27369. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27370. var options = {
  27371. width: width,
  27372. height: height,
  27373. subdivisions: subdivisions,
  27374. minHeight: minHeight,
  27375. maxHeight: maxHeight,
  27376. updatable: updatable,
  27377. onReady: onReady
  27378. };
  27379. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27380. };
  27381. /**
  27382. * Creates a tube mesh.
  27383. * 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.
  27384. * Please consider using the same method from the MeshBuilder class instead.
  27385. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27386. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27387. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27388. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27389. * 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.
  27390. * It must return a radius value (positive float) :
  27391. * ```javascript
  27392. * var radiusFunction = function(i, distance) {
  27393. * // do things
  27394. * return radius; }
  27395. * ```
  27396. * 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
  27397. * 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
  27398. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27399. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27401. */
  27402. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27403. var options = {
  27404. path: path,
  27405. radius: radius,
  27406. tessellation: tessellation,
  27407. radiusFunction: radiusFunction,
  27408. arc: 1,
  27409. cap: cap,
  27410. updatable: updatable,
  27411. sideOrientation: sideOrientation,
  27412. instance: instance
  27413. };
  27414. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27415. };
  27416. /**
  27417. * Creates a polyhedron mesh.
  27418. * Please consider using the same method from the MeshBuilder class instead.
  27419. * 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
  27420. * to choose the wanted type.
  27421. * The parameter `size` (positive float, default 1) sets the polygon size.
  27422. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27423. * 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`.
  27424. * 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
  27425. * 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)`).
  27426. * 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
  27427. * 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.
  27428. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27429. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27431. */
  27432. Mesh.CreatePolyhedron = function (name, options, scene) {
  27433. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27434. };
  27435. /**
  27436. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27437. * Please consider using the same method from the MeshBuilder class instead.
  27438. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27439. * 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`).
  27440. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27441. * 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.
  27442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27445. */
  27446. Mesh.CreateIcoSphere = function (name, options, scene) {
  27447. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27448. };
  27449. /**
  27450. * Creates a decal mesh.
  27451. * Please consider using the same method from the MeshBuilder class instead.
  27452. * 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.
  27453. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27454. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27455. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27456. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27457. */
  27458. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27459. var options = {
  27460. position: position,
  27461. normal: normal,
  27462. size: size,
  27463. angle: angle
  27464. };
  27465. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27466. };
  27467. // Skeletons
  27468. /**
  27469. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27470. */
  27471. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27472. if (!this._sourcePositions) {
  27473. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27474. if (!source) {
  27475. return this._sourcePositions;
  27476. }
  27477. this._sourcePositions = new Float32Array(source);
  27478. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27479. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27480. }
  27481. }
  27482. return this._sourcePositions;
  27483. };
  27484. /**
  27485. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27486. */
  27487. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27488. if (!this._sourceNormals) {
  27489. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27490. if (!source) {
  27491. return this._sourceNormals;
  27492. }
  27493. this._sourceNormals = new Float32Array(source);
  27494. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27495. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27496. }
  27497. }
  27498. return this._sourceNormals;
  27499. };
  27500. /**
  27501. * Updates the vertex buffer by applying transformation from the bones.
  27502. * Returns the Mesh.
  27503. *
  27504. * @param {skeleton} skeleton to apply
  27505. */
  27506. Mesh.prototype.applySkeleton = function (skeleton) {
  27507. if (!this.geometry) {
  27508. return this;
  27509. }
  27510. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27511. return this;
  27512. }
  27513. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27514. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27515. return this;
  27516. }
  27517. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27518. return this;
  27519. }
  27520. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27521. return this;
  27522. }
  27523. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27524. return this;
  27525. }
  27526. if (!this._sourcePositions) {
  27527. var submeshes = this.subMeshes.slice();
  27528. this.setPositionsForCPUSkinning();
  27529. this.subMeshes = submeshes;
  27530. }
  27531. if (!this._sourceNormals) {
  27532. this.setNormalsForCPUSkinning();
  27533. }
  27534. // positionsData checks for not being Float32Array will only pass at most once
  27535. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27536. if (!positionsData) {
  27537. return this;
  27538. }
  27539. if (!(positionsData instanceof Float32Array)) {
  27540. positionsData = new Float32Array(positionsData);
  27541. }
  27542. // normalsData checks for not being Float32Array will only pass at most once
  27543. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27544. if (!normalsData) {
  27545. return this;
  27546. }
  27547. if (!(normalsData instanceof Float32Array)) {
  27548. normalsData = new Float32Array(normalsData);
  27549. }
  27550. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27551. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27552. if (!matricesWeightsData || !matricesIndicesData) {
  27553. return this;
  27554. }
  27555. var needExtras = this.numBoneInfluencers > 4;
  27556. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27557. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27558. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27559. var tempVector3 = BABYLON.Vector3.Zero();
  27560. var finalMatrix = new BABYLON.Matrix();
  27561. var tempMatrix = new BABYLON.Matrix();
  27562. var matWeightIdx = 0;
  27563. var inf;
  27564. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27565. var weight;
  27566. for (inf = 0; inf < 4; inf++) {
  27567. weight = matricesWeightsData[matWeightIdx + inf];
  27568. if (weight > 0) {
  27569. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27570. finalMatrix.addToSelf(tempMatrix);
  27571. }
  27572. else
  27573. break;
  27574. }
  27575. if (needExtras) {
  27576. for (inf = 0; inf < 4; inf++) {
  27577. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27578. if (weight > 0) {
  27579. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27580. finalMatrix.addToSelf(tempMatrix);
  27581. }
  27582. else
  27583. break;
  27584. }
  27585. }
  27586. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27587. tempVector3.toArray(positionsData, index);
  27588. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27589. tempVector3.toArray(normalsData, index);
  27590. finalMatrix.reset();
  27591. }
  27592. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27593. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27594. return this;
  27595. };
  27596. // Tools
  27597. /**
  27598. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27599. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27600. */
  27601. Mesh.MinMax = function (meshes) {
  27602. var minVector = null;
  27603. var maxVector = null;
  27604. meshes.forEach(function (mesh, index, array) {
  27605. var boundingInfo = mesh.getBoundingInfo();
  27606. var boundingBox = boundingInfo.boundingBox;
  27607. if (!minVector || !maxVector) {
  27608. minVector = boundingBox.minimumWorld;
  27609. maxVector = boundingBox.maximumWorld;
  27610. }
  27611. else {
  27612. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27613. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27614. }
  27615. });
  27616. if (!minVector || !maxVector) {
  27617. return {
  27618. min: BABYLON.Vector3.Zero(),
  27619. max: BABYLON.Vector3.Zero()
  27620. };
  27621. }
  27622. return {
  27623. min: minVector,
  27624. max: maxVector
  27625. };
  27626. };
  27627. /**
  27628. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27629. */
  27630. Mesh.Center = function (meshesOrMinMaxVector) {
  27631. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27632. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27633. };
  27634. /**
  27635. * Merge the array of meshes into a single mesh for performance reasons.
  27636. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27637. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27638. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27639. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27640. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27641. */
  27642. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27643. if (disposeSource === void 0) { disposeSource = true; }
  27644. var index;
  27645. if (!allow32BitsIndices) {
  27646. var totalVertices = 0;
  27647. // Counting vertices
  27648. for (index = 0; index < meshes.length; index++) {
  27649. if (meshes[index]) {
  27650. totalVertices += meshes[index].getTotalVertices();
  27651. if (totalVertices > 65536) {
  27652. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27653. return null;
  27654. }
  27655. }
  27656. }
  27657. }
  27658. // Merge
  27659. var vertexData = null;
  27660. var otherVertexData;
  27661. var indiceArray = new Array();
  27662. var source = null;
  27663. for (index = 0; index < meshes.length; index++) {
  27664. if (meshes[index]) {
  27665. meshes[index].computeWorldMatrix(true);
  27666. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27667. otherVertexData.transform(meshes[index].getWorldMatrix());
  27668. if (vertexData) {
  27669. vertexData.merge(otherVertexData);
  27670. }
  27671. else {
  27672. vertexData = otherVertexData;
  27673. source = meshes[index];
  27674. }
  27675. if (subdivideWithSubMeshes) {
  27676. indiceArray.push(meshes[index].getTotalIndices());
  27677. }
  27678. }
  27679. }
  27680. source = source;
  27681. if (!meshSubclass) {
  27682. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27683. }
  27684. vertexData.applyToMesh(meshSubclass);
  27685. // Setting properties
  27686. meshSubclass.material = source.material;
  27687. meshSubclass.checkCollisions = source.checkCollisions;
  27688. // Cleaning
  27689. if (disposeSource) {
  27690. for (index = 0; index < meshes.length; index++) {
  27691. if (meshes[index]) {
  27692. meshes[index].dispose();
  27693. }
  27694. }
  27695. }
  27696. // Subdivide
  27697. if (subdivideWithSubMeshes) {
  27698. //-- Suppresions du submesh global
  27699. meshSubclass.releaseSubMeshes();
  27700. index = 0;
  27701. var offset = 0;
  27702. //-- aplique la subdivision en fonction du tableau d'indices
  27703. while (index < indiceArray.length) {
  27704. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27705. offset += indiceArray[index];
  27706. index++;
  27707. }
  27708. }
  27709. return meshSubclass;
  27710. };
  27711. // Consts
  27712. Mesh._FRONTSIDE = 0;
  27713. Mesh._BACKSIDE = 1;
  27714. Mesh._DOUBLESIDE = 2;
  27715. Mesh._DEFAULTSIDE = 0;
  27716. Mesh._NO_CAP = 0;
  27717. Mesh._CAP_START = 1;
  27718. Mesh._CAP_END = 2;
  27719. Mesh._CAP_ALL = 3;
  27720. return Mesh;
  27721. }(BABYLON.AbstractMesh));
  27722. BABYLON.Mesh = Mesh;
  27723. })(BABYLON || (BABYLON = {}));
  27724. //# sourceMappingURL=babylon.mesh.js.map
  27725. var BABYLON;
  27726. (function (BABYLON) {
  27727. var BaseSubMesh = /** @class */ (function () {
  27728. function BaseSubMesh() {
  27729. }
  27730. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27731. get: function () {
  27732. return this._materialEffect;
  27733. },
  27734. enumerable: true,
  27735. configurable: true
  27736. });
  27737. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27738. if (defines === void 0) { defines = null; }
  27739. if (this._materialEffect === effect) {
  27740. if (!effect) {
  27741. this._materialDefines = null;
  27742. }
  27743. return;
  27744. }
  27745. this._materialDefines = defines;
  27746. this._materialEffect = effect;
  27747. };
  27748. return BaseSubMesh;
  27749. }());
  27750. BABYLON.BaseSubMesh = BaseSubMesh;
  27751. var SubMesh = /** @class */ (function (_super) {
  27752. __extends(SubMesh, _super);
  27753. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27754. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27755. var _this = _super.call(this) || this;
  27756. _this.materialIndex = materialIndex;
  27757. _this.verticesStart = verticesStart;
  27758. _this.verticesCount = verticesCount;
  27759. _this.indexStart = indexStart;
  27760. _this.indexCount = indexCount;
  27761. _this._renderId = 0;
  27762. _this._mesh = mesh;
  27763. _this._renderingMesh = renderingMesh || mesh;
  27764. mesh.subMeshes.push(_this);
  27765. _this._trianglePlanes = [];
  27766. _this._id = mesh.subMeshes.length - 1;
  27767. if (createBoundingBox) {
  27768. _this.refreshBoundingInfo();
  27769. mesh.computeWorldMatrix(true);
  27770. }
  27771. return _this;
  27772. }
  27773. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27774. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27775. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27776. };
  27777. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27778. get: function () {
  27779. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27780. },
  27781. enumerable: true,
  27782. configurable: true
  27783. });
  27784. /**
  27785. * Returns the submesh BoudingInfo object.
  27786. */
  27787. SubMesh.prototype.getBoundingInfo = function () {
  27788. if (this.IsGlobal) {
  27789. return this._mesh.getBoundingInfo();
  27790. }
  27791. return this._boundingInfo;
  27792. };
  27793. /**
  27794. * Sets the submesh BoundingInfo.
  27795. * Return the SubMesh.
  27796. */
  27797. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27798. this._boundingInfo = boundingInfo;
  27799. return this;
  27800. };
  27801. /**
  27802. * Returns the mesh of the current submesh.
  27803. */
  27804. SubMesh.prototype.getMesh = function () {
  27805. return this._mesh;
  27806. };
  27807. /**
  27808. * Returns the rendering mesh of the submesh.
  27809. */
  27810. SubMesh.prototype.getRenderingMesh = function () {
  27811. return this._renderingMesh;
  27812. };
  27813. /**
  27814. * Returns the submesh material.
  27815. */
  27816. SubMesh.prototype.getMaterial = function () {
  27817. var rootMaterial = this._renderingMesh.material;
  27818. if (rootMaterial === null || rootMaterial === undefined) {
  27819. return this._mesh.getScene().defaultMaterial;
  27820. }
  27821. else if (rootMaterial.getSubMaterial) {
  27822. var multiMaterial = rootMaterial;
  27823. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27824. if (this._currentMaterial !== effectiveMaterial) {
  27825. this._currentMaterial = effectiveMaterial;
  27826. this._materialDefines = null;
  27827. }
  27828. return effectiveMaterial;
  27829. }
  27830. return rootMaterial;
  27831. };
  27832. // Methods
  27833. /**
  27834. * Sets a new updated BoundingInfo object to the submesh.
  27835. * Returns the SubMesh.
  27836. */
  27837. SubMesh.prototype.refreshBoundingInfo = function () {
  27838. this._lastColliderWorldVertices = null;
  27839. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27840. return this;
  27841. }
  27842. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27843. if (!data) {
  27844. this._boundingInfo = this._mesh.getBoundingInfo();
  27845. return this;
  27846. }
  27847. var indices = this._renderingMesh.getIndices();
  27848. var extend;
  27849. //is this the only submesh?
  27850. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27851. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27852. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27853. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27854. }
  27855. else {
  27856. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27857. }
  27858. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27859. return this;
  27860. };
  27861. SubMesh.prototype._checkCollision = function (collider) {
  27862. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27863. return boundingInfo._checkCollision(collider);
  27864. };
  27865. /**
  27866. * Updates the submesh BoundingInfo.
  27867. * Returns the Submesh.
  27868. */
  27869. SubMesh.prototype.updateBoundingInfo = function (world) {
  27870. var boundingInfo = this.getBoundingInfo();
  27871. if (!boundingInfo) {
  27872. this.refreshBoundingInfo();
  27873. boundingInfo = this.getBoundingInfo();
  27874. }
  27875. boundingInfo.update(world);
  27876. return this;
  27877. };
  27878. /**
  27879. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27880. * Boolean returned.
  27881. */
  27882. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27883. var boundingInfo = this.getBoundingInfo();
  27884. if (!boundingInfo) {
  27885. return false;
  27886. }
  27887. return boundingInfo.isInFrustum(frustumPlanes);
  27888. };
  27889. /**
  27890. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27891. * Boolean returned.
  27892. */
  27893. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27894. var boundingInfo = this.getBoundingInfo();
  27895. if (!boundingInfo) {
  27896. return false;
  27897. }
  27898. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27899. };
  27900. /**
  27901. * Renders the submesh.
  27902. * Returns it.
  27903. */
  27904. SubMesh.prototype.render = function (enableAlphaMode) {
  27905. this._renderingMesh.render(this, enableAlphaMode);
  27906. return this;
  27907. };
  27908. /**
  27909. * Returns a new Index Buffer.
  27910. * Type returned : WebGLBuffer.
  27911. */
  27912. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27913. if (!this._linesIndexBuffer) {
  27914. var linesIndices = [];
  27915. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27916. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27917. }
  27918. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27919. this.linesIndexCount = linesIndices.length;
  27920. }
  27921. return this._linesIndexBuffer;
  27922. };
  27923. /**
  27924. * True is the passed Ray intersects the submesh bounding box.
  27925. * Boolean returned.
  27926. */
  27927. SubMesh.prototype.canIntersects = function (ray) {
  27928. var boundingInfo = this.getBoundingInfo();
  27929. if (!boundingInfo) {
  27930. return false;
  27931. }
  27932. return ray.intersectsBox(boundingInfo.boundingBox);
  27933. };
  27934. /**
  27935. * Returns an object IntersectionInfo.
  27936. */
  27937. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27938. var intersectInfo = null;
  27939. // LineMesh first as it's also a Mesh...
  27940. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27941. var lineMesh = this._mesh;
  27942. // Line test
  27943. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27944. var p0 = positions[indices[index]];
  27945. var p1 = positions[indices[index + 1]];
  27946. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27947. if (length < 0) {
  27948. continue;
  27949. }
  27950. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27951. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27952. if (fastCheck) {
  27953. break;
  27954. }
  27955. }
  27956. }
  27957. }
  27958. else {
  27959. // Triangles test
  27960. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27961. var p0 = positions[indices[index]];
  27962. var p1 = positions[indices[index + 1]];
  27963. var p2 = positions[indices[index + 2]];
  27964. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27965. if (currentIntersectInfo) {
  27966. if (currentIntersectInfo.distance < 0) {
  27967. continue;
  27968. }
  27969. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27970. intersectInfo = currentIntersectInfo;
  27971. intersectInfo.faceId = index / 3;
  27972. if (fastCheck) {
  27973. break;
  27974. }
  27975. }
  27976. }
  27977. }
  27978. }
  27979. return intersectInfo;
  27980. };
  27981. SubMesh.prototype._rebuild = function () {
  27982. if (this._linesIndexBuffer) {
  27983. this._linesIndexBuffer = null;
  27984. }
  27985. };
  27986. // Clone
  27987. /**
  27988. * Creates a new Submesh from the passed Mesh.
  27989. */
  27990. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27991. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27992. if (!this.IsGlobal) {
  27993. var boundingInfo = this.getBoundingInfo();
  27994. if (!boundingInfo) {
  27995. return result;
  27996. }
  27997. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  27998. }
  27999. return result;
  28000. };
  28001. // Dispose
  28002. /**
  28003. * Disposes the Submesh.
  28004. * Returns nothing.
  28005. */
  28006. SubMesh.prototype.dispose = function () {
  28007. if (this._linesIndexBuffer) {
  28008. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28009. this._linesIndexBuffer = null;
  28010. }
  28011. // Remove from mesh
  28012. var index = this._mesh.subMeshes.indexOf(this);
  28013. this._mesh.subMeshes.splice(index, 1);
  28014. };
  28015. // Statics
  28016. /**
  28017. * Creates a new Submesh from the passed parameters :
  28018. * - materialIndex (integer) : the index of the main mesh material.
  28019. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28020. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28021. * - mesh (Mesh) : the main mesh to create the submesh from.
  28022. * - renderingMesh (optional Mesh) : rendering mesh.
  28023. */
  28024. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28025. var minVertexIndex = Number.MAX_VALUE;
  28026. var maxVertexIndex = -Number.MAX_VALUE;
  28027. renderingMesh = (renderingMesh || mesh);
  28028. var indices = renderingMesh.getIndices();
  28029. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28030. var vertexIndex = indices[index];
  28031. if (vertexIndex < minVertexIndex)
  28032. minVertexIndex = vertexIndex;
  28033. if (vertexIndex > maxVertexIndex)
  28034. maxVertexIndex = vertexIndex;
  28035. }
  28036. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28037. };
  28038. return SubMesh;
  28039. }(BaseSubMesh));
  28040. BABYLON.SubMesh = SubMesh;
  28041. })(BABYLON || (BABYLON = {}));
  28042. //# sourceMappingURL=babylon.subMesh.js.map
  28043. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28044. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28045. s = arguments[i];
  28046. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28047. t[p] = s[p];
  28048. }
  28049. return t;
  28050. };
  28051. var BABYLON;
  28052. (function (BABYLON) {
  28053. var MaterialDefines = /** @class */ (function () {
  28054. function MaterialDefines() {
  28055. this._isDirty = true;
  28056. this._areLightsDirty = true;
  28057. this._areAttributesDirty = true;
  28058. this._areTexturesDirty = true;
  28059. this._areFresnelDirty = true;
  28060. this._areMiscDirty = true;
  28061. this._areImageProcessingDirty = true;
  28062. this._normals = false;
  28063. this._uvs = false;
  28064. this._needNormals = false;
  28065. this._needUVs = false;
  28066. }
  28067. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28068. get: function () {
  28069. return this._isDirty;
  28070. },
  28071. enumerable: true,
  28072. configurable: true
  28073. });
  28074. MaterialDefines.prototype.markAsProcessed = function () {
  28075. this._isDirty = false;
  28076. this._areAttributesDirty = false;
  28077. this._areTexturesDirty = false;
  28078. this._areFresnelDirty = false;
  28079. this._areLightsDirty = false;
  28080. this._areMiscDirty = false;
  28081. this._areImageProcessingDirty = false;
  28082. };
  28083. MaterialDefines.prototype.markAsUnprocessed = function () {
  28084. this._isDirty = true;
  28085. };
  28086. MaterialDefines.prototype.markAllAsDirty = function () {
  28087. this._areTexturesDirty = true;
  28088. this._areAttributesDirty = true;
  28089. this._areLightsDirty = true;
  28090. this._areFresnelDirty = true;
  28091. this._areMiscDirty = true;
  28092. this._areImageProcessingDirty = true;
  28093. this._isDirty = true;
  28094. };
  28095. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28096. this._areImageProcessingDirty = true;
  28097. this._isDirty = true;
  28098. };
  28099. MaterialDefines.prototype.markAsLightDirty = function () {
  28100. this._areLightsDirty = true;
  28101. this._isDirty = true;
  28102. };
  28103. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28104. this._areAttributesDirty = true;
  28105. this._isDirty = true;
  28106. };
  28107. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28108. this._areTexturesDirty = true;
  28109. this._isDirty = true;
  28110. };
  28111. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28112. this._areFresnelDirty = true;
  28113. this._isDirty = true;
  28114. };
  28115. MaterialDefines.prototype.markAsMiscDirty = function () {
  28116. this._areMiscDirty = true;
  28117. this._isDirty = true;
  28118. };
  28119. MaterialDefines.prototype.rebuild = function () {
  28120. if (this._keys) {
  28121. delete this._keys;
  28122. }
  28123. this._keys = [];
  28124. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28125. var key = _a[_i];
  28126. if (key[0] === "_") {
  28127. continue;
  28128. }
  28129. this._keys.push(key);
  28130. }
  28131. };
  28132. MaterialDefines.prototype.isEqual = function (other) {
  28133. if (this._keys.length !== other._keys.length) {
  28134. return false;
  28135. }
  28136. for (var index = 0; index < this._keys.length; index++) {
  28137. var prop = this._keys[index];
  28138. if (this[prop] !== other[prop]) {
  28139. return false;
  28140. }
  28141. }
  28142. return true;
  28143. };
  28144. MaterialDefines.prototype.cloneTo = function (other) {
  28145. if (this._keys.length !== other._keys.length) {
  28146. other._keys = this._keys.slice(0);
  28147. }
  28148. for (var index = 0; index < this._keys.length; index++) {
  28149. var prop = this._keys[index];
  28150. other[prop] = this[prop];
  28151. }
  28152. };
  28153. MaterialDefines.prototype.reset = function () {
  28154. for (var index = 0; index < this._keys.length; index++) {
  28155. var prop = this._keys[index];
  28156. if (typeof (this[prop]) === "number") {
  28157. this[prop] = 0;
  28158. }
  28159. else {
  28160. this[prop] = false;
  28161. }
  28162. }
  28163. };
  28164. MaterialDefines.prototype.toString = function () {
  28165. var result = "";
  28166. for (var index = 0; index < this._keys.length; index++) {
  28167. var prop = this._keys[index];
  28168. var value = this[prop];
  28169. if (typeof (value) === "number") {
  28170. result += "#define " + prop + " " + this[prop] + "\n";
  28171. }
  28172. else if (value) {
  28173. result += "#define " + prop + "\n";
  28174. }
  28175. }
  28176. return result;
  28177. };
  28178. return MaterialDefines;
  28179. }());
  28180. BABYLON.MaterialDefines = MaterialDefines;
  28181. var Material = /** @class */ (function () {
  28182. function Material(name, scene, doNotAdd) {
  28183. this.checkReadyOnEveryCall = false;
  28184. this.checkReadyOnlyOnce = false;
  28185. this.state = "";
  28186. this.alpha = 1.0;
  28187. this._backFaceCulling = true;
  28188. this.doNotSerialize = false;
  28189. this.storeEffectOnSubMeshes = false;
  28190. /**
  28191. * An event triggered when the material is disposed.
  28192. * @type {BABYLON.Observable}
  28193. */
  28194. this.onDisposeObservable = new BABYLON.Observable();
  28195. /**
  28196. * An event triggered when the material is bound.
  28197. * @type {BABYLON.Observable}
  28198. */
  28199. this.onBindObservable = new BABYLON.Observable();
  28200. /**
  28201. * An event triggered when the material is unbound.
  28202. * @type {BABYLON.Observable}
  28203. */
  28204. this.onUnBindObservable = new BABYLON.Observable();
  28205. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28206. this._needDepthPrePass = false;
  28207. this.disableDepthWrite = false;
  28208. this.forceDepthWrite = false;
  28209. this.separateCullingPass = false;
  28210. this._fogEnabled = true;
  28211. this.pointSize = 1.0;
  28212. this.zOffset = 0;
  28213. this._wasPreviouslyReady = false;
  28214. this._fillMode = Material.TriangleFillMode;
  28215. this.name = name;
  28216. this.id = name || BABYLON.Tools.RandomId();
  28217. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28218. if (this._scene.useRightHandedSystem) {
  28219. this.sideOrientation = Material.ClockWiseSideOrientation;
  28220. }
  28221. else {
  28222. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28223. }
  28224. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28225. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28226. if (!doNotAdd) {
  28227. this._scene.materials.push(this);
  28228. }
  28229. }
  28230. Object.defineProperty(Material, "TriangleFillMode", {
  28231. get: function () {
  28232. return Material._TriangleFillMode;
  28233. },
  28234. enumerable: true,
  28235. configurable: true
  28236. });
  28237. Object.defineProperty(Material, "WireFrameFillMode", {
  28238. get: function () {
  28239. return Material._WireFrameFillMode;
  28240. },
  28241. enumerable: true,
  28242. configurable: true
  28243. });
  28244. Object.defineProperty(Material, "PointFillMode", {
  28245. get: function () {
  28246. return Material._PointFillMode;
  28247. },
  28248. enumerable: true,
  28249. configurable: true
  28250. });
  28251. Object.defineProperty(Material, "PointListDrawMode", {
  28252. get: function () {
  28253. return Material._PointListDrawMode;
  28254. },
  28255. enumerable: true,
  28256. configurable: true
  28257. });
  28258. Object.defineProperty(Material, "LineListDrawMode", {
  28259. get: function () {
  28260. return Material._LineListDrawMode;
  28261. },
  28262. enumerable: true,
  28263. configurable: true
  28264. });
  28265. Object.defineProperty(Material, "LineLoopDrawMode", {
  28266. get: function () {
  28267. return Material._LineLoopDrawMode;
  28268. },
  28269. enumerable: true,
  28270. configurable: true
  28271. });
  28272. Object.defineProperty(Material, "LineStripDrawMode", {
  28273. get: function () {
  28274. return Material._LineStripDrawMode;
  28275. },
  28276. enumerable: true,
  28277. configurable: true
  28278. });
  28279. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28280. get: function () {
  28281. return Material._TriangleStripDrawMode;
  28282. },
  28283. enumerable: true,
  28284. configurable: true
  28285. });
  28286. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28287. get: function () {
  28288. return Material._TriangleFanDrawMode;
  28289. },
  28290. enumerable: true,
  28291. configurable: true
  28292. });
  28293. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28294. get: function () {
  28295. return Material._ClockWiseSideOrientation;
  28296. },
  28297. enumerable: true,
  28298. configurable: true
  28299. });
  28300. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28301. get: function () {
  28302. return Material._CounterClockWiseSideOrientation;
  28303. },
  28304. enumerable: true,
  28305. configurable: true
  28306. });
  28307. Object.defineProperty(Material, "TextureDirtyFlag", {
  28308. get: function () {
  28309. return Material._TextureDirtyFlag;
  28310. },
  28311. enumerable: true,
  28312. configurable: true
  28313. });
  28314. Object.defineProperty(Material, "LightDirtyFlag", {
  28315. get: function () {
  28316. return Material._LightDirtyFlag;
  28317. },
  28318. enumerable: true,
  28319. configurable: true
  28320. });
  28321. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28322. get: function () {
  28323. return Material._FresnelDirtyFlag;
  28324. },
  28325. enumerable: true,
  28326. configurable: true
  28327. });
  28328. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28329. get: function () {
  28330. return Material._AttributesDirtyFlag;
  28331. },
  28332. enumerable: true,
  28333. configurable: true
  28334. });
  28335. Object.defineProperty(Material, "MiscDirtyFlag", {
  28336. get: function () {
  28337. return Material._MiscDirtyFlag;
  28338. },
  28339. enumerable: true,
  28340. configurable: true
  28341. });
  28342. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28343. get: function () {
  28344. return this._backFaceCulling;
  28345. },
  28346. set: function (value) {
  28347. if (this._backFaceCulling === value) {
  28348. return;
  28349. }
  28350. this._backFaceCulling = value;
  28351. this.markAsDirty(Material.TextureDirtyFlag);
  28352. },
  28353. enumerable: true,
  28354. configurable: true
  28355. });
  28356. Object.defineProperty(Material.prototype, "onDispose", {
  28357. set: function (callback) {
  28358. if (this._onDisposeObserver) {
  28359. this.onDisposeObservable.remove(this._onDisposeObserver);
  28360. }
  28361. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28362. },
  28363. enumerable: true,
  28364. configurable: true
  28365. });
  28366. Object.defineProperty(Material.prototype, "onBind", {
  28367. set: function (callback) {
  28368. if (this._onBindObserver) {
  28369. this.onBindObservable.remove(this._onBindObserver);
  28370. }
  28371. this._onBindObserver = this.onBindObservable.add(callback);
  28372. },
  28373. enumerable: true,
  28374. configurable: true
  28375. });
  28376. Object.defineProperty(Material.prototype, "alphaMode", {
  28377. get: function () {
  28378. return this._alphaMode;
  28379. },
  28380. set: function (value) {
  28381. if (this._alphaMode === value) {
  28382. return;
  28383. }
  28384. this._alphaMode = value;
  28385. this.markAsDirty(Material.TextureDirtyFlag);
  28386. },
  28387. enumerable: true,
  28388. configurable: true
  28389. });
  28390. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28391. get: function () {
  28392. return this._needDepthPrePass;
  28393. },
  28394. set: function (value) {
  28395. if (this._needDepthPrePass === value) {
  28396. return;
  28397. }
  28398. this._needDepthPrePass = value;
  28399. if (this._needDepthPrePass) {
  28400. this.checkReadyOnEveryCall = true;
  28401. }
  28402. },
  28403. enumerable: true,
  28404. configurable: true
  28405. });
  28406. Object.defineProperty(Material.prototype, "fogEnabled", {
  28407. get: function () {
  28408. return this._fogEnabled;
  28409. },
  28410. set: function (value) {
  28411. if (this._fogEnabled === value) {
  28412. return;
  28413. }
  28414. this._fogEnabled = value;
  28415. this.markAsDirty(Material.MiscDirtyFlag);
  28416. },
  28417. enumerable: true,
  28418. configurable: true
  28419. });
  28420. Object.defineProperty(Material.prototype, "wireframe", {
  28421. get: function () {
  28422. return this._fillMode === Material.WireFrameFillMode;
  28423. },
  28424. set: function (value) {
  28425. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28426. },
  28427. enumerable: true,
  28428. configurable: true
  28429. });
  28430. Object.defineProperty(Material.prototype, "pointsCloud", {
  28431. get: function () {
  28432. return this._fillMode === Material.PointFillMode;
  28433. },
  28434. set: function (value) {
  28435. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28436. },
  28437. enumerable: true,
  28438. configurable: true
  28439. });
  28440. Object.defineProperty(Material.prototype, "fillMode", {
  28441. get: function () {
  28442. return this._fillMode;
  28443. },
  28444. set: function (value) {
  28445. if (this._fillMode === value) {
  28446. return;
  28447. }
  28448. this._fillMode = value;
  28449. this.markAsDirty(Material.MiscDirtyFlag);
  28450. },
  28451. enumerable: true,
  28452. configurable: true
  28453. });
  28454. /**
  28455. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28456. * subclasses should override adding information pertainent to themselves
  28457. */
  28458. Material.prototype.toString = function (fullDetails) {
  28459. var ret = "Name: " + this.name;
  28460. if (fullDetails) {
  28461. }
  28462. return ret;
  28463. };
  28464. /**
  28465. * Child classes can use it to update shaders
  28466. */
  28467. Material.prototype.getClassName = function () {
  28468. return "Material";
  28469. };
  28470. Object.defineProperty(Material.prototype, "isFrozen", {
  28471. get: function () {
  28472. return this.checkReadyOnlyOnce;
  28473. },
  28474. enumerable: true,
  28475. configurable: true
  28476. });
  28477. Material.prototype.freeze = function () {
  28478. this.checkReadyOnlyOnce = true;
  28479. };
  28480. Material.prototype.unfreeze = function () {
  28481. this.checkReadyOnlyOnce = false;
  28482. };
  28483. Material.prototype.isReady = function (mesh, useInstances) {
  28484. return true;
  28485. };
  28486. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28487. return false;
  28488. };
  28489. Material.prototype.getEffect = function () {
  28490. return this._effect;
  28491. };
  28492. Material.prototype.getScene = function () {
  28493. return this._scene;
  28494. };
  28495. Material.prototype.needAlphaBlending = function () {
  28496. return (this.alpha < 1.0);
  28497. };
  28498. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28499. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28500. };
  28501. Material.prototype.needAlphaTesting = function () {
  28502. return false;
  28503. };
  28504. Material.prototype.getAlphaTestTexture = function () {
  28505. return null;
  28506. };
  28507. Material.prototype.markDirty = function () {
  28508. this._wasPreviouslyReady = false;
  28509. };
  28510. Material.prototype._preBind = function (effect, overrideOrientation) {
  28511. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28512. var engine = this._scene.getEngine();
  28513. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28514. var reverse = orientation === Material.ClockWiseSideOrientation;
  28515. engine.enableEffect(effect ? effect : this._effect);
  28516. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28517. return reverse;
  28518. };
  28519. Material.prototype.bind = function (world, mesh) {
  28520. };
  28521. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28522. };
  28523. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28524. };
  28525. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28526. sceneUbo.bindToEffect(effect, "Scene");
  28527. };
  28528. Material.prototype.bindView = function (effect) {
  28529. if (!this._useUBO) {
  28530. effect.setMatrix("view", this.getScene().getViewMatrix());
  28531. }
  28532. else {
  28533. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28534. }
  28535. };
  28536. Material.prototype.bindViewProjection = function (effect) {
  28537. if (!this._useUBO) {
  28538. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28539. }
  28540. else {
  28541. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28542. }
  28543. };
  28544. Material.prototype._afterBind = function (mesh) {
  28545. this._scene._cachedMaterial = this;
  28546. if (mesh) {
  28547. this._scene._cachedVisibility = mesh.visibility;
  28548. }
  28549. else {
  28550. this._scene._cachedVisibility = 1;
  28551. }
  28552. if (mesh) {
  28553. this.onBindObservable.notifyObservers(mesh);
  28554. }
  28555. if (this.disableDepthWrite) {
  28556. var engine = this._scene.getEngine();
  28557. this._cachedDepthWriteState = engine.getDepthWrite();
  28558. engine.setDepthWrite(false);
  28559. }
  28560. };
  28561. Material.prototype.unbind = function () {
  28562. this.onUnBindObservable.notifyObservers(this);
  28563. if (this.disableDepthWrite) {
  28564. var engine = this._scene.getEngine();
  28565. engine.setDepthWrite(this._cachedDepthWriteState);
  28566. }
  28567. };
  28568. Material.prototype.getActiveTextures = function () {
  28569. return [];
  28570. };
  28571. Material.prototype.hasTexture = function (texture) {
  28572. return false;
  28573. };
  28574. Material.prototype.clone = function (name) {
  28575. return null;
  28576. };
  28577. Material.prototype.getBindedMeshes = function () {
  28578. var result = new Array();
  28579. for (var index = 0; index < this._scene.meshes.length; index++) {
  28580. var mesh = this._scene.meshes[index];
  28581. if (mesh.material === this) {
  28582. result.push(mesh);
  28583. }
  28584. }
  28585. return result;
  28586. };
  28587. /**
  28588. * Force shader compilation including textures ready check
  28589. */
  28590. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28591. var _this = this;
  28592. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28593. var subMesh = new BABYLON.BaseSubMesh();
  28594. var scene = this.getScene();
  28595. var engine = scene.getEngine();
  28596. var checkReady = function () {
  28597. if (!_this._scene || !_this._scene.getEngine()) {
  28598. return;
  28599. }
  28600. if (subMesh._materialDefines) {
  28601. subMesh._materialDefines._renderId = -1;
  28602. }
  28603. var alphaTestState = engine.getAlphaTesting();
  28604. var clipPlaneState = scene.clipPlane;
  28605. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28606. if (localOptions.clipPlane) {
  28607. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28608. }
  28609. if (_this.storeEffectOnSubMeshes) {
  28610. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28611. if (onCompiled) {
  28612. onCompiled(_this);
  28613. }
  28614. }
  28615. else {
  28616. setTimeout(checkReady, 16);
  28617. }
  28618. }
  28619. else {
  28620. if (_this.isReady(mesh)) {
  28621. if (onCompiled) {
  28622. onCompiled(_this);
  28623. }
  28624. }
  28625. else {
  28626. setTimeout(checkReady, 16);
  28627. }
  28628. }
  28629. engine.setAlphaTesting(alphaTestState);
  28630. if (options && options.clipPlane) {
  28631. scene.clipPlane = clipPlaneState;
  28632. }
  28633. };
  28634. checkReady();
  28635. };
  28636. Material.prototype.markAsDirty = function (flag) {
  28637. if (flag & Material.TextureDirtyFlag) {
  28638. this._markAllSubMeshesAsTexturesDirty();
  28639. }
  28640. if (flag & Material.LightDirtyFlag) {
  28641. this._markAllSubMeshesAsLightsDirty();
  28642. }
  28643. if (flag & Material.FresnelDirtyFlag) {
  28644. this._markAllSubMeshesAsFresnelDirty();
  28645. }
  28646. if (flag & Material.AttributesDirtyFlag) {
  28647. this._markAllSubMeshesAsAttributesDirty();
  28648. }
  28649. if (flag & Material.MiscDirtyFlag) {
  28650. this._markAllSubMeshesAsMiscDirty();
  28651. }
  28652. this.getScene().resetCachedMaterial();
  28653. };
  28654. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28655. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28656. var mesh = _a[_i];
  28657. if (!mesh.subMeshes) {
  28658. continue;
  28659. }
  28660. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28661. var subMesh = _c[_b];
  28662. if (subMesh.getMaterial() !== this) {
  28663. continue;
  28664. }
  28665. if (!subMesh._materialDefines) {
  28666. continue;
  28667. }
  28668. func(subMesh._materialDefines);
  28669. }
  28670. }
  28671. };
  28672. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28673. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28674. };
  28675. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28676. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28677. };
  28678. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28679. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28680. };
  28681. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28682. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28683. };
  28684. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28685. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28686. };
  28687. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28688. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28689. };
  28690. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28691. // Animations
  28692. this.getScene().stopAnimation(this);
  28693. // Remove from scene
  28694. var index = this._scene.materials.indexOf(this);
  28695. if (index >= 0) {
  28696. this._scene.materials.splice(index, 1);
  28697. }
  28698. // Remove from meshes
  28699. for (index = 0; index < this._scene.meshes.length; index++) {
  28700. var mesh = this._scene.meshes[index];
  28701. if (mesh.material === this) {
  28702. mesh.material = null;
  28703. if (mesh.geometry) {
  28704. var geometry = (mesh.geometry);
  28705. if (this.storeEffectOnSubMeshes) {
  28706. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28707. var subMesh = _a[_i];
  28708. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28709. if (forceDisposeEffect && subMesh._materialEffect) {
  28710. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28711. }
  28712. }
  28713. }
  28714. else {
  28715. geometry._releaseVertexArrayObject(this._effect);
  28716. }
  28717. }
  28718. }
  28719. }
  28720. this._uniformBuffer.dispose();
  28721. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28722. if (forceDisposeEffect && this._effect) {
  28723. if (!this.storeEffectOnSubMeshes) {
  28724. this._scene.getEngine()._releaseEffect(this._effect);
  28725. }
  28726. this._effect = null;
  28727. }
  28728. // Callback
  28729. this.onDisposeObservable.notifyObservers(this);
  28730. this.onDisposeObservable.clear();
  28731. this.onBindObservable.clear();
  28732. this.onUnBindObservable.clear();
  28733. };
  28734. Material.prototype.serialize = function () {
  28735. return BABYLON.SerializationHelper.Serialize(this);
  28736. };
  28737. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28738. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28739. multiMaterial.id = parsedMultiMaterial.id;
  28740. if (BABYLON.Tags) {
  28741. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28742. }
  28743. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28744. var subMatId = parsedMultiMaterial.materials[matIndex];
  28745. if (subMatId) {
  28746. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28747. }
  28748. else {
  28749. multiMaterial.subMaterials.push(null);
  28750. }
  28751. }
  28752. return multiMaterial;
  28753. };
  28754. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28755. if (!parsedMaterial.customType) {
  28756. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28757. }
  28758. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28759. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28760. if (!BABYLON.LegacyPBRMaterial) {
  28761. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28762. return;
  28763. }
  28764. }
  28765. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28766. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28767. ;
  28768. };
  28769. // Triangle views
  28770. Material._TriangleFillMode = 0;
  28771. Material._WireFrameFillMode = 1;
  28772. Material._PointFillMode = 2;
  28773. // Draw modes
  28774. Material._PointListDrawMode = 3;
  28775. Material._LineListDrawMode = 4;
  28776. Material._LineLoopDrawMode = 5;
  28777. Material._LineStripDrawMode = 6;
  28778. Material._TriangleStripDrawMode = 7;
  28779. Material._TriangleFanDrawMode = 8;
  28780. Material._ClockWiseSideOrientation = 0;
  28781. Material._CounterClockWiseSideOrientation = 1;
  28782. Material._TextureDirtyFlag = 1;
  28783. Material._LightDirtyFlag = 2;
  28784. Material._FresnelDirtyFlag = 4;
  28785. Material._AttributesDirtyFlag = 8;
  28786. Material._MiscDirtyFlag = 16;
  28787. __decorate([
  28788. BABYLON.serialize()
  28789. ], Material.prototype, "id", void 0);
  28790. __decorate([
  28791. BABYLON.serialize()
  28792. ], Material.prototype, "name", void 0);
  28793. __decorate([
  28794. BABYLON.serialize()
  28795. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28796. __decorate([
  28797. BABYLON.serialize()
  28798. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28799. __decorate([
  28800. BABYLON.serialize()
  28801. ], Material.prototype, "state", void 0);
  28802. __decorate([
  28803. BABYLON.serialize()
  28804. ], Material.prototype, "alpha", void 0);
  28805. __decorate([
  28806. BABYLON.serialize("backFaceCulling")
  28807. ], Material.prototype, "_backFaceCulling", void 0);
  28808. __decorate([
  28809. BABYLON.serialize()
  28810. ], Material.prototype, "sideOrientation", void 0);
  28811. __decorate([
  28812. BABYLON.serialize("alphaMode")
  28813. ], Material.prototype, "_alphaMode", void 0);
  28814. __decorate([
  28815. BABYLON.serialize()
  28816. ], Material.prototype, "_needDepthPrePass", void 0);
  28817. __decorate([
  28818. BABYLON.serialize()
  28819. ], Material.prototype, "disableDepthWrite", void 0);
  28820. __decorate([
  28821. BABYLON.serialize()
  28822. ], Material.prototype, "forceDepthWrite", void 0);
  28823. __decorate([
  28824. BABYLON.serialize()
  28825. ], Material.prototype, "separateCullingPass", void 0);
  28826. __decorate([
  28827. BABYLON.serialize("fogEnabled")
  28828. ], Material.prototype, "_fogEnabled", void 0);
  28829. __decorate([
  28830. BABYLON.serialize()
  28831. ], Material.prototype, "pointSize", void 0);
  28832. __decorate([
  28833. BABYLON.serialize()
  28834. ], Material.prototype, "zOffset", void 0);
  28835. __decorate([
  28836. BABYLON.serialize()
  28837. ], Material.prototype, "wireframe", null);
  28838. __decorate([
  28839. BABYLON.serialize()
  28840. ], Material.prototype, "pointsCloud", null);
  28841. __decorate([
  28842. BABYLON.serialize()
  28843. ], Material.prototype, "fillMode", null);
  28844. return Material;
  28845. }());
  28846. BABYLON.Material = Material;
  28847. })(BABYLON || (BABYLON = {}));
  28848. //# sourceMappingURL=babylon.material.js.map
  28849. var BABYLON;
  28850. (function (BABYLON) {
  28851. var UniformBuffer = /** @class */ (function () {
  28852. /**
  28853. * Uniform buffer objects.
  28854. *
  28855. * Handles blocks of uniform on the GPU.
  28856. *
  28857. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28858. *
  28859. * For more information, please refer to :
  28860. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28861. */
  28862. function UniformBuffer(engine, data, dynamic) {
  28863. this._engine = engine;
  28864. this._noUBO = !engine.supportsUniformBuffers;
  28865. this._dynamic = dynamic;
  28866. this._data = data || [];
  28867. this._uniformLocations = {};
  28868. this._uniformSizes = {};
  28869. this._uniformLocationPointer = 0;
  28870. this._needSync = false;
  28871. if (this._noUBO) {
  28872. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28873. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28874. this.updateFloat = this._updateFloatForEffect;
  28875. this.updateFloat2 = this._updateFloat2ForEffect;
  28876. this.updateFloat3 = this._updateFloat3ForEffect;
  28877. this.updateFloat4 = this._updateFloat4ForEffect;
  28878. this.updateMatrix = this._updateMatrixForEffect;
  28879. this.updateVector3 = this._updateVector3ForEffect;
  28880. this.updateVector4 = this._updateVector4ForEffect;
  28881. this.updateColor3 = this._updateColor3ForEffect;
  28882. this.updateColor4 = this._updateColor4ForEffect;
  28883. }
  28884. else {
  28885. this._engine._uniformBuffers.push(this);
  28886. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28887. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28888. this.updateFloat = this._updateFloatForUniform;
  28889. this.updateFloat2 = this._updateFloat2ForUniform;
  28890. this.updateFloat3 = this._updateFloat3ForUniform;
  28891. this.updateFloat4 = this._updateFloat4ForUniform;
  28892. this.updateMatrix = this._updateMatrixForUniform;
  28893. this.updateVector3 = this._updateVector3ForUniform;
  28894. this.updateVector4 = this._updateVector4ForUniform;
  28895. this.updateColor3 = this._updateColor3ForUniform;
  28896. this.updateColor4 = this._updateColor4ForUniform;
  28897. }
  28898. }
  28899. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28900. // Properties
  28901. /**
  28902. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28903. * or just falling back on setUniformXXX calls.
  28904. */
  28905. get: function () {
  28906. return !this._noUBO;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28912. /**
  28913. * Indicates if the WebGL underlying uniform buffer is in sync
  28914. * with the javascript cache data.
  28915. */
  28916. get: function () {
  28917. return !this._needSync;
  28918. },
  28919. enumerable: true,
  28920. configurable: true
  28921. });
  28922. /**
  28923. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28924. * Also, a dynamic UniformBuffer will disable cache verification and always
  28925. * update the underlying WebGL uniform buffer to the GPU.
  28926. */
  28927. UniformBuffer.prototype.isDynamic = function () {
  28928. return this._dynamic !== undefined;
  28929. };
  28930. /**
  28931. * The data cache on JS side.
  28932. */
  28933. UniformBuffer.prototype.getData = function () {
  28934. return this._bufferData;
  28935. };
  28936. /**
  28937. * The underlying WebGL Uniform buffer.
  28938. */
  28939. UniformBuffer.prototype.getBuffer = function () {
  28940. return this._buffer;
  28941. };
  28942. /**
  28943. * std140 layout specifies how to align data within an UBO structure.
  28944. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28945. * for specs.
  28946. */
  28947. UniformBuffer.prototype._fillAlignment = function (size) {
  28948. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28949. // and 4x4 matrices
  28950. // TODO : change if other types are used
  28951. var alignment;
  28952. if (size <= 2) {
  28953. alignment = size;
  28954. }
  28955. else {
  28956. alignment = 4;
  28957. }
  28958. if ((this._uniformLocationPointer % alignment) !== 0) {
  28959. var oldPointer = this._uniformLocationPointer;
  28960. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28961. var diff = this._uniformLocationPointer - oldPointer;
  28962. for (var i = 0; i < diff; i++) {
  28963. this._data.push(0);
  28964. }
  28965. }
  28966. };
  28967. /**
  28968. * Adds an uniform in the buffer.
  28969. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28970. * for the layout to be correct !
  28971. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28972. * @param {number|number[]} size Data size, or data directly.
  28973. */
  28974. UniformBuffer.prototype.addUniform = function (name, size) {
  28975. if (this._noUBO) {
  28976. return;
  28977. }
  28978. if (this._uniformLocations[name] !== undefined) {
  28979. // Already existing uniform
  28980. return;
  28981. }
  28982. // This function must be called in the order of the shader layout !
  28983. // size can be the size of the uniform, or data directly
  28984. var data;
  28985. if (size instanceof Array) {
  28986. data = size;
  28987. size = data.length;
  28988. }
  28989. else {
  28990. size = size;
  28991. data = [];
  28992. // Fill with zeros
  28993. for (var i = 0; i < size; i++) {
  28994. data.push(0);
  28995. }
  28996. }
  28997. this._fillAlignment(size);
  28998. this._uniformSizes[name] = size;
  28999. this._uniformLocations[name] = this._uniformLocationPointer;
  29000. this._uniformLocationPointer += size;
  29001. for (var i = 0; i < size; i++) {
  29002. this._data.push(data[i]);
  29003. }
  29004. this._needSync = true;
  29005. };
  29006. /**
  29007. * Wrapper for addUniform.
  29008. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29009. * @param {Matrix} mat A 4x4 matrix.
  29010. */
  29011. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29012. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29013. };
  29014. /**
  29015. * Wrapper for addUniform.
  29016. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29017. * @param {number} x
  29018. * @param {number} y
  29019. */
  29020. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29021. var temp = [x, y];
  29022. this.addUniform(name, temp);
  29023. };
  29024. /**
  29025. * Wrapper for addUniform.
  29026. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29027. * @param {number} x
  29028. * @param {number} y
  29029. * @param {number} z
  29030. */
  29031. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29032. var temp = [x, y, z];
  29033. this.addUniform(name, temp);
  29034. };
  29035. /**
  29036. * Wrapper for addUniform.
  29037. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29038. * @param {Color3} color
  29039. */
  29040. UniformBuffer.prototype.addColor3 = function (name, color) {
  29041. var temp = new Array();
  29042. color.toArray(temp);
  29043. this.addUniform(name, temp);
  29044. };
  29045. /**
  29046. * Wrapper for addUniform.
  29047. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29048. * @param {Color3} color
  29049. * @param {number} alpha
  29050. */
  29051. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29052. var temp = new Array();
  29053. color.toArray(temp);
  29054. temp.push(alpha);
  29055. this.addUniform(name, temp);
  29056. };
  29057. /**
  29058. * Wrapper for addUniform.
  29059. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29060. * @param {Vector3} vector
  29061. */
  29062. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29063. var temp = new Array();
  29064. vector.toArray(temp);
  29065. this.addUniform(name, temp);
  29066. };
  29067. /**
  29068. * Wrapper for addUniform.
  29069. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29070. */
  29071. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29072. this.addUniform(name, 12);
  29073. };
  29074. /**
  29075. * Wrapper for addUniform.
  29076. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29077. */
  29078. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29079. this.addUniform(name, 8);
  29080. };
  29081. /**
  29082. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29083. */
  29084. UniformBuffer.prototype.create = function () {
  29085. if (this._noUBO) {
  29086. return;
  29087. }
  29088. if (this._buffer) {
  29089. return; // nothing to do
  29090. }
  29091. // See spec, alignment must be filled as a vec4
  29092. this._fillAlignment(4);
  29093. this._bufferData = new Float32Array(this._data);
  29094. this._rebuild();
  29095. this._needSync = true;
  29096. };
  29097. UniformBuffer.prototype._rebuild = function () {
  29098. if (this._noUBO) {
  29099. return;
  29100. }
  29101. if (this._dynamic) {
  29102. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29103. }
  29104. else {
  29105. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29106. }
  29107. };
  29108. /**
  29109. * Updates the WebGL Uniform Buffer on the GPU.
  29110. * If the `dynamic` flag is set to true, no cache comparison is done.
  29111. * Otherwise, the buffer will be updated only if the cache differs.
  29112. */
  29113. UniformBuffer.prototype.update = function () {
  29114. if (!this._buffer) {
  29115. this.create();
  29116. return;
  29117. }
  29118. if (!this._dynamic && !this._needSync) {
  29119. return;
  29120. }
  29121. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29122. this._needSync = false;
  29123. };
  29124. /**
  29125. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29126. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29127. * @param {number[]|Float32Array} data Flattened data
  29128. * @param {number} size Size of the data.
  29129. */
  29130. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29131. var location = this._uniformLocations[uniformName];
  29132. if (location === undefined) {
  29133. if (this._buffer) {
  29134. // Cannot add an uniform if the buffer is already created
  29135. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29136. return;
  29137. }
  29138. this.addUniform(uniformName, size);
  29139. location = this._uniformLocations[uniformName];
  29140. }
  29141. if (!this._buffer) {
  29142. this.create();
  29143. }
  29144. if (!this._dynamic) {
  29145. // Cache for static uniform buffers
  29146. var changed = false;
  29147. for (var i = 0; i < size; i++) {
  29148. if (this._bufferData[location + i] !== data[i]) {
  29149. changed = true;
  29150. this._bufferData[location + i] = data[i];
  29151. }
  29152. }
  29153. this._needSync = this._needSync || changed;
  29154. }
  29155. else {
  29156. // No cache for dynamic
  29157. for (var i = 0; i < size; i++) {
  29158. this._bufferData[location + i] = data[i];
  29159. }
  29160. }
  29161. };
  29162. // Update methods
  29163. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29164. // To match std140, matrix must be realigned
  29165. for (var i = 0; i < 3; i++) {
  29166. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29167. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29168. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29169. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29170. }
  29171. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29172. };
  29173. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29174. this._currentEffect.setMatrix3x3(name, matrix);
  29175. };
  29176. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29177. this._currentEffect.setMatrix2x2(name, matrix);
  29178. };
  29179. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29180. // To match std140, matrix must be realigned
  29181. for (var i = 0; i < 2; i++) {
  29182. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29183. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29184. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29185. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29186. }
  29187. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29188. };
  29189. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29190. this._currentEffect.setFloat(name, x);
  29191. };
  29192. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29193. UniformBuffer._tempBuffer[0] = x;
  29194. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29195. };
  29196. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29197. if (suffix === void 0) { suffix = ""; }
  29198. this._currentEffect.setFloat2(name + suffix, x, y);
  29199. };
  29200. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29201. if (suffix === void 0) { suffix = ""; }
  29202. UniformBuffer._tempBuffer[0] = x;
  29203. UniformBuffer._tempBuffer[1] = y;
  29204. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29205. };
  29206. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29207. if (suffix === void 0) { suffix = ""; }
  29208. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29209. };
  29210. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29211. if (suffix === void 0) { suffix = ""; }
  29212. UniformBuffer._tempBuffer[0] = x;
  29213. UniformBuffer._tempBuffer[1] = y;
  29214. UniformBuffer._tempBuffer[2] = z;
  29215. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29216. };
  29217. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29218. if (suffix === void 0) { suffix = ""; }
  29219. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29220. };
  29221. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29222. if (suffix === void 0) { suffix = ""; }
  29223. UniformBuffer._tempBuffer[0] = x;
  29224. UniformBuffer._tempBuffer[1] = y;
  29225. UniformBuffer._tempBuffer[2] = z;
  29226. UniformBuffer._tempBuffer[3] = w;
  29227. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29228. };
  29229. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29230. this._currentEffect.setMatrix(name, mat);
  29231. };
  29232. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29233. this.updateUniform(name, mat.toArray(), 16);
  29234. };
  29235. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29236. this._currentEffect.setVector3(name, vector);
  29237. };
  29238. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29239. vector.toArray(UniformBuffer._tempBuffer);
  29240. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29241. };
  29242. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29243. this._currentEffect.setVector4(name, vector);
  29244. };
  29245. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29246. vector.toArray(UniformBuffer._tempBuffer);
  29247. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29248. };
  29249. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29250. if (suffix === void 0) { suffix = ""; }
  29251. this._currentEffect.setColor3(name + suffix, color);
  29252. };
  29253. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29254. if (suffix === void 0) { suffix = ""; }
  29255. color.toArray(UniformBuffer._tempBuffer);
  29256. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29257. };
  29258. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29259. if (suffix === void 0) { suffix = ""; }
  29260. this._currentEffect.setColor4(name + suffix, color, alpha);
  29261. };
  29262. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29263. if (suffix === void 0) { suffix = ""; }
  29264. color.toArray(UniformBuffer._tempBuffer);
  29265. UniformBuffer._tempBuffer[3] = alpha;
  29266. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29267. };
  29268. /**
  29269. * Sets a sampler uniform on the effect.
  29270. * @param {string} name Name of the sampler.
  29271. * @param {Texture} texture
  29272. */
  29273. UniformBuffer.prototype.setTexture = function (name, texture) {
  29274. this._currentEffect.setTexture(name, texture);
  29275. };
  29276. /**
  29277. * Directly updates the value of the uniform in the cache AND on the GPU.
  29278. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29279. * @param {number[]|Float32Array} data Flattened data
  29280. */
  29281. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29282. this.updateUniform(uniformName, data, data.length);
  29283. this.update();
  29284. };
  29285. /**
  29286. * Binds this uniform buffer to an effect.
  29287. * @param {Effect} effect
  29288. * @param {string} name Name of the uniform block in the shader.
  29289. */
  29290. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29291. this._currentEffect = effect;
  29292. if (this._noUBO || !this._buffer) {
  29293. return;
  29294. }
  29295. effect.bindUniformBuffer(this._buffer, name);
  29296. };
  29297. /**
  29298. * Disposes the uniform buffer.
  29299. */
  29300. UniformBuffer.prototype.dispose = function () {
  29301. if (this._noUBO) {
  29302. return;
  29303. }
  29304. var index = this._engine._uniformBuffers.indexOf(this);
  29305. if (index !== -1) {
  29306. this._engine._uniformBuffers.splice(index, 1);
  29307. }
  29308. if (!this._buffer) {
  29309. return;
  29310. }
  29311. if (this._engine._releaseBuffer(this._buffer)) {
  29312. this._buffer = null;
  29313. }
  29314. };
  29315. // Pool for avoiding memory leaks
  29316. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29317. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29318. return UniformBuffer;
  29319. }());
  29320. BABYLON.UniformBuffer = UniformBuffer;
  29321. })(BABYLON || (BABYLON = {}));
  29322. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29323. var BABYLON;
  29324. (function (BABYLON) {
  29325. var VertexData = /** @class */ (function () {
  29326. function VertexData() {
  29327. }
  29328. VertexData.prototype.set = function (data, kind) {
  29329. switch (kind) {
  29330. case BABYLON.VertexBuffer.PositionKind:
  29331. this.positions = data;
  29332. break;
  29333. case BABYLON.VertexBuffer.NormalKind:
  29334. this.normals = data;
  29335. break;
  29336. case BABYLON.VertexBuffer.TangentKind:
  29337. this.tangents = data;
  29338. break;
  29339. case BABYLON.VertexBuffer.UVKind:
  29340. this.uvs = data;
  29341. break;
  29342. case BABYLON.VertexBuffer.UV2Kind:
  29343. this.uvs2 = data;
  29344. break;
  29345. case BABYLON.VertexBuffer.UV3Kind:
  29346. this.uvs3 = data;
  29347. break;
  29348. case BABYLON.VertexBuffer.UV4Kind:
  29349. this.uvs4 = data;
  29350. break;
  29351. case BABYLON.VertexBuffer.UV5Kind:
  29352. this.uvs5 = data;
  29353. break;
  29354. case BABYLON.VertexBuffer.UV6Kind:
  29355. this.uvs6 = data;
  29356. break;
  29357. case BABYLON.VertexBuffer.ColorKind:
  29358. this.colors = data;
  29359. break;
  29360. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29361. this.matricesIndices = data;
  29362. break;
  29363. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29364. this.matricesWeights = data;
  29365. break;
  29366. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29367. this.matricesIndicesExtra = data;
  29368. break;
  29369. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29370. this.matricesWeightsExtra = data;
  29371. break;
  29372. }
  29373. };
  29374. /**
  29375. * Associates the vertexData to the passed Mesh.
  29376. * Sets it as updatable or not (default `false`).
  29377. * Returns the VertexData.
  29378. */
  29379. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29380. this._applyTo(mesh, updatable);
  29381. return this;
  29382. };
  29383. /**
  29384. * Associates the vertexData to the passed Geometry.
  29385. * Sets it as updatable or not (default `false`).
  29386. * Returns the VertexData.
  29387. */
  29388. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29389. this._applyTo(geometry, updatable);
  29390. return this;
  29391. };
  29392. /**
  29393. * Updates the associated mesh.
  29394. * Returns the VertexData.
  29395. */
  29396. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29397. this._update(mesh);
  29398. return this;
  29399. };
  29400. /**
  29401. * Updates the associated geometry.
  29402. * Returns the VertexData.
  29403. */
  29404. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29405. this._update(geometry);
  29406. return this;
  29407. };
  29408. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29409. if (updatable === void 0) { updatable = false; }
  29410. if (this.positions) {
  29411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29412. }
  29413. if (this.normals) {
  29414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29415. }
  29416. if (this.tangents) {
  29417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29418. }
  29419. if (this.uvs) {
  29420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29421. }
  29422. if (this.uvs2) {
  29423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29424. }
  29425. if (this.uvs3) {
  29426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29427. }
  29428. if (this.uvs4) {
  29429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29430. }
  29431. if (this.uvs5) {
  29432. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29433. }
  29434. if (this.uvs6) {
  29435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29436. }
  29437. if (this.colors) {
  29438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29439. }
  29440. if (this.matricesIndices) {
  29441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29442. }
  29443. if (this.matricesWeights) {
  29444. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29445. }
  29446. if (this.matricesIndicesExtra) {
  29447. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29448. }
  29449. if (this.matricesWeightsExtra) {
  29450. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29451. }
  29452. if (this.indices) {
  29453. meshOrGeometry.setIndices(this.indices, null, updatable);
  29454. }
  29455. return this;
  29456. };
  29457. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29458. if (this.positions) {
  29459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29460. }
  29461. if (this.normals) {
  29462. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29463. }
  29464. if (this.tangents) {
  29465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29466. }
  29467. if (this.uvs) {
  29468. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29469. }
  29470. if (this.uvs2) {
  29471. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29472. }
  29473. if (this.uvs3) {
  29474. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29475. }
  29476. if (this.uvs4) {
  29477. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29478. }
  29479. if (this.uvs5) {
  29480. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29481. }
  29482. if (this.uvs6) {
  29483. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29484. }
  29485. if (this.colors) {
  29486. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29487. }
  29488. if (this.matricesIndices) {
  29489. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29490. }
  29491. if (this.matricesWeights) {
  29492. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29493. }
  29494. if (this.matricesIndicesExtra) {
  29495. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29496. }
  29497. if (this.matricesWeightsExtra) {
  29498. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29499. }
  29500. if (this.indices) {
  29501. meshOrGeometry.setIndices(this.indices, null);
  29502. }
  29503. return this;
  29504. };
  29505. /**
  29506. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29507. * Returns the VertexData.
  29508. */
  29509. VertexData.prototype.transform = function (matrix) {
  29510. var transformed = BABYLON.Vector3.Zero();
  29511. var index;
  29512. if (this.positions) {
  29513. var position = BABYLON.Vector3.Zero();
  29514. for (index = 0; index < this.positions.length; index += 3) {
  29515. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29516. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29517. this.positions[index] = transformed.x;
  29518. this.positions[index + 1] = transformed.y;
  29519. this.positions[index + 2] = transformed.z;
  29520. }
  29521. }
  29522. if (this.normals) {
  29523. var normal = BABYLON.Vector3.Zero();
  29524. for (index = 0; index < this.normals.length; index += 3) {
  29525. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29526. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29527. this.normals[index] = transformed.x;
  29528. this.normals[index + 1] = transformed.y;
  29529. this.normals[index + 2] = transformed.z;
  29530. }
  29531. }
  29532. if (this.tangents) {
  29533. var tangent = BABYLON.Vector4.Zero();
  29534. var tangentTransformed = BABYLON.Vector4.Zero();
  29535. for (index = 0; index < this.tangents.length; index += 4) {
  29536. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29537. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29538. this.tangents[index] = tangentTransformed.x;
  29539. this.tangents[index + 1] = tangentTransformed.y;
  29540. this.tangents[index + 2] = tangentTransformed.z;
  29541. this.tangents[index + 3] = tangentTransformed.w;
  29542. }
  29543. }
  29544. return this;
  29545. };
  29546. /**
  29547. * Merges the passed VertexData into the current one.
  29548. * Returns the modified VertexData.
  29549. */
  29550. VertexData.prototype.merge = function (other, options) {
  29551. options = options || {};
  29552. if (other.indices) {
  29553. if (!this.indices) {
  29554. this.indices = [];
  29555. }
  29556. var offset = this.positions ? this.positions.length / 3 : 0;
  29557. for (var index = 0; index < other.indices.length; index++) {
  29558. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29559. this.indices.push(other.indices[index] + offset);
  29560. }
  29561. }
  29562. this.positions = this._mergeElement(this.positions, other.positions);
  29563. if (!this.positions) {
  29564. return this;
  29565. }
  29566. var count = this.positions.length / 3;
  29567. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29568. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29569. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29570. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29571. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29572. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29573. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29574. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29575. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29576. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29577. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29578. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29579. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29580. return this;
  29581. };
  29582. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29583. if (length === void 0) { length = 0; }
  29584. if (defaultValue === void 0) { defaultValue = 0; }
  29585. if (!other && !source) {
  29586. return null;
  29587. }
  29588. if (!other) {
  29589. var padding = new Float32Array(source.length);
  29590. padding.fill(defaultValue);
  29591. return this._mergeElement(source, padding, length);
  29592. }
  29593. if (!source) {
  29594. if (length === 0 || length === other.length) {
  29595. return other;
  29596. }
  29597. var padding = new Float32Array(length - other.length);
  29598. padding.fill(defaultValue);
  29599. return this._mergeElement(padding, other, length);
  29600. }
  29601. var len = other.length + source.length;
  29602. var isSrcTypedArray = source instanceof Float32Array;
  29603. var isOthTypedArray = other instanceof Float32Array;
  29604. // use non-loop method when the source is Float32Array
  29605. if (isSrcTypedArray) {
  29606. var ret32 = new Float32Array(len);
  29607. ret32.set(source);
  29608. ret32.set(other, source.length);
  29609. return ret32;
  29610. // source is number[], when other is also use concat
  29611. }
  29612. else if (!isOthTypedArray) {
  29613. return source.concat(other);
  29614. // source is a number[], but other is a Float32Array, loop required
  29615. }
  29616. else {
  29617. var ret = source.slice(0); // copy source to a separate array
  29618. for (var i = 0, len = other.length; i < len; i++) {
  29619. ret.push(other[i]);
  29620. }
  29621. return ret;
  29622. }
  29623. };
  29624. /**
  29625. * Serializes the VertexData.
  29626. * Returns a serialized object.
  29627. */
  29628. VertexData.prototype.serialize = function () {
  29629. var serializationObject = this.serialize();
  29630. if (this.positions) {
  29631. serializationObject.positions = this.positions;
  29632. }
  29633. if (this.normals) {
  29634. serializationObject.normals = this.normals;
  29635. }
  29636. if (this.tangents) {
  29637. serializationObject.tangents = this.tangents;
  29638. }
  29639. if (this.uvs) {
  29640. serializationObject.uvs = this.uvs;
  29641. }
  29642. if (this.uvs2) {
  29643. serializationObject.uvs2 = this.uvs2;
  29644. }
  29645. if (this.uvs3) {
  29646. serializationObject.uvs3 = this.uvs3;
  29647. }
  29648. if (this.uvs4) {
  29649. serializationObject.uvs4 = this.uvs4;
  29650. }
  29651. if (this.uvs5) {
  29652. serializationObject.uvs5 = this.uvs5;
  29653. }
  29654. if (this.uvs6) {
  29655. serializationObject.uvs6 = this.uvs6;
  29656. }
  29657. if (this.colors) {
  29658. serializationObject.colors = this.colors;
  29659. }
  29660. if (this.matricesIndices) {
  29661. serializationObject.matricesIndices = this.matricesIndices;
  29662. serializationObject.matricesIndices._isExpanded = true;
  29663. }
  29664. if (this.matricesWeights) {
  29665. serializationObject.matricesWeights = this.matricesWeights;
  29666. }
  29667. if (this.matricesIndicesExtra) {
  29668. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29669. serializationObject.matricesIndicesExtra._isExpanded = true;
  29670. }
  29671. if (this.matricesWeightsExtra) {
  29672. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29673. }
  29674. serializationObject.indices = this.indices;
  29675. return serializationObject;
  29676. };
  29677. // Statics
  29678. /**
  29679. * Returns the object VertexData associated to the passed mesh.
  29680. */
  29681. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29682. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29683. };
  29684. /**
  29685. * Returns the object VertexData associated to the passed geometry.
  29686. */
  29687. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29688. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29689. };
  29690. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29691. var result = new VertexData();
  29692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29693. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29694. }
  29695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29696. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29697. }
  29698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29699. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29700. }
  29701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29702. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29703. }
  29704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29705. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29706. }
  29707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29708. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29709. }
  29710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29711. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29712. }
  29713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29714. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29715. }
  29716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29717. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29718. }
  29719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29720. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29721. }
  29722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29723. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29724. }
  29725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29726. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29727. }
  29728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29729. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29730. }
  29731. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29732. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29733. }
  29734. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29735. return result;
  29736. };
  29737. /**
  29738. * Creates the vertexData of the Ribbon.
  29739. */
  29740. VertexData.CreateRibbon = function (options) {
  29741. var pathArray = options.pathArray;
  29742. var closeArray = options.closeArray || false;
  29743. var closePath = options.closePath || false;
  29744. var invertUV = options.invertUV || false;
  29745. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29746. var offset = options.offset || defaultOffset;
  29747. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29748. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29749. var customUV = options.uvs;
  29750. var customColors = options.colors;
  29751. var positions = [];
  29752. var indices = [];
  29753. var normals = [];
  29754. var uvs = [];
  29755. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29756. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29757. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29758. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29759. var minlg; // minimal length among all paths from pathArray
  29760. var lg = []; // array of path lengths : nb of vertex per path
  29761. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29762. var p; // path iterator
  29763. var i; // point iterator
  29764. var j; // point iterator
  29765. // if single path in pathArray
  29766. if (pathArray.length < 2) {
  29767. var ar1 = [];
  29768. var ar2 = [];
  29769. for (i = 0; i < pathArray[0].length - offset; i++) {
  29770. ar1.push(pathArray[0][i]);
  29771. ar2.push(pathArray[0][i + offset]);
  29772. }
  29773. pathArray = [ar1, ar2];
  29774. }
  29775. // positions and horizontal distances (u)
  29776. var idc = 0;
  29777. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29778. var path;
  29779. var l;
  29780. minlg = pathArray[0].length;
  29781. var vectlg;
  29782. var dist;
  29783. for (p = 0; p < pathArray.length; p++) {
  29784. uTotalDistance[p] = 0;
  29785. us[p] = [0];
  29786. path = pathArray[p];
  29787. l = path.length;
  29788. minlg = (minlg < l) ? minlg : l;
  29789. j = 0;
  29790. while (j < l) {
  29791. positions.push(path[j].x, path[j].y, path[j].z);
  29792. if (j > 0) {
  29793. vectlg = path[j].subtract(path[j - 1]).length();
  29794. dist = vectlg + uTotalDistance[p];
  29795. us[p].push(dist);
  29796. uTotalDistance[p] = dist;
  29797. }
  29798. j++;
  29799. }
  29800. if (closePath) {
  29801. j--;
  29802. positions.push(path[0].x, path[0].y, path[0].z);
  29803. vectlg = path[j].subtract(path[0]).length();
  29804. dist = vectlg + uTotalDistance[p];
  29805. us[p].push(dist);
  29806. uTotalDistance[p] = dist;
  29807. }
  29808. lg[p] = l + closePathCorr;
  29809. idx[p] = idc;
  29810. idc += (l + closePathCorr);
  29811. }
  29812. // vertical distances (v)
  29813. var path1;
  29814. var path2;
  29815. var vertex1 = null;
  29816. var vertex2 = null;
  29817. for (i = 0; i < minlg + closePathCorr; i++) {
  29818. vTotalDistance[i] = 0;
  29819. vs[i] = [0];
  29820. for (p = 0; p < pathArray.length - 1; p++) {
  29821. path1 = pathArray[p];
  29822. path2 = pathArray[p + 1];
  29823. if (i === minlg) {
  29824. vertex1 = path1[0];
  29825. vertex2 = path2[0];
  29826. }
  29827. else {
  29828. vertex1 = path1[i];
  29829. vertex2 = path2[i];
  29830. }
  29831. vectlg = vertex2.subtract(vertex1).length();
  29832. dist = vectlg + vTotalDistance[i];
  29833. vs[i].push(dist);
  29834. vTotalDistance[i] = dist;
  29835. }
  29836. if (closeArray && vertex2 && vertex1) {
  29837. path1 = pathArray[p];
  29838. path2 = pathArray[0];
  29839. if (i === minlg) {
  29840. vertex2 = path2[0];
  29841. }
  29842. vectlg = vertex2.subtract(vertex1).length();
  29843. dist = vectlg + vTotalDistance[i];
  29844. vTotalDistance[i] = dist;
  29845. }
  29846. }
  29847. // uvs
  29848. var u;
  29849. var v;
  29850. if (customUV) {
  29851. for (p = 0; p < customUV.length; p++) {
  29852. uvs.push(customUV[p].x, customUV[p].y);
  29853. }
  29854. }
  29855. else {
  29856. for (p = 0; p < pathArray.length; p++) {
  29857. for (i = 0; i < minlg + closePathCorr; i++) {
  29858. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29859. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29860. if (invertUV) {
  29861. uvs.push(v, u);
  29862. }
  29863. else {
  29864. uvs.push(u, v);
  29865. }
  29866. }
  29867. }
  29868. }
  29869. // indices
  29870. p = 0; // path index
  29871. var pi = 0; // positions array index
  29872. var l1 = lg[p] - 1; // path1 length
  29873. var l2 = lg[p + 1] - 1; // path2 length
  29874. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29875. var shft = idx[1] - idx[0]; // shift
  29876. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29877. while (pi <= min && p < path1nb) {
  29878. // 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
  29879. indices.push(pi, pi + shft, pi + 1);
  29880. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29881. pi += 1;
  29882. if (pi === min) {
  29883. p++;
  29884. if (p === lg.length - 1) {
  29885. shft = idx[0] - idx[p];
  29886. l1 = lg[p] - 1;
  29887. l2 = lg[0] - 1;
  29888. }
  29889. else {
  29890. shft = idx[p + 1] - idx[p];
  29891. l1 = lg[p] - 1;
  29892. l2 = lg[p + 1] - 1;
  29893. }
  29894. pi = idx[p];
  29895. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29896. }
  29897. }
  29898. // normals
  29899. VertexData.ComputeNormals(positions, indices, normals);
  29900. if (closePath) {
  29901. var indexFirst = 0;
  29902. var indexLast = 0;
  29903. for (p = 0; p < pathArray.length; p++) {
  29904. indexFirst = idx[p] * 3;
  29905. if (p + 1 < pathArray.length) {
  29906. indexLast = (idx[p + 1] - 1) * 3;
  29907. }
  29908. else {
  29909. indexLast = normals.length - 3;
  29910. }
  29911. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29912. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29913. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29914. normals[indexLast] = normals[indexFirst];
  29915. normals[indexLast + 1] = normals[indexFirst + 1];
  29916. normals[indexLast + 2] = normals[indexFirst + 2];
  29917. }
  29918. }
  29919. // sides
  29920. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29921. // Colors
  29922. var colors = null;
  29923. if (customColors) {
  29924. colors = new Float32Array(customColors.length * 4);
  29925. for (var c = 0; c < customColors.length; c++) {
  29926. colors[c * 4] = customColors[c].r;
  29927. colors[c * 4 + 1] = customColors[c].g;
  29928. colors[c * 4 + 2] = customColors[c].b;
  29929. colors[c * 4 + 3] = customColors[c].a;
  29930. }
  29931. }
  29932. // Result
  29933. var vertexData = new VertexData();
  29934. var positions32 = new Float32Array(positions);
  29935. var normals32 = new Float32Array(normals);
  29936. var uvs32 = new Float32Array(uvs);
  29937. vertexData.indices = indices;
  29938. vertexData.positions = positions32;
  29939. vertexData.normals = normals32;
  29940. vertexData.uvs = uvs32;
  29941. if (colors) {
  29942. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29943. }
  29944. if (closePath) {
  29945. vertexData._idx = idx;
  29946. }
  29947. return vertexData;
  29948. };
  29949. /**
  29950. * Creates the VertexData of the Box.
  29951. */
  29952. VertexData.CreateBox = function (options) {
  29953. var normalsSource = [
  29954. new BABYLON.Vector3(0, 0, 1),
  29955. new BABYLON.Vector3(0, 0, -1),
  29956. new BABYLON.Vector3(1, 0, 0),
  29957. new BABYLON.Vector3(-1, 0, 0),
  29958. new BABYLON.Vector3(0, 1, 0),
  29959. new BABYLON.Vector3(0, -1, 0)
  29960. ];
  29961. var indices = [];
  29962. var positions = [];
  29963. var normals = [];
  29964. var uvs = [];
  29965. var width = options.width || options.size || 1;
  29966. var height = options.height || options.size || 1;
  29967. var depth = options.depth || options.size || 1;
  29968. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29969. var faceUV = options.faceUV || new Array(6);
  29970. var faceColors = options.faceColors;
  29971. var colors = [];
  29972. // default face colors and UV if undefined
  29973. for (var f = 0; f < 6; f++) {
  29974. if (faceUV[f] === undefined) {
  29975. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29976. }
  29977. if (faceColors && faceColors[f] === undefined) {
  29978. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29979. }
  29980. }
  29981. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29982. // Create each face in turn.
  29983. for (var index = 0; index < normalsSource.length; index++) {
  29984. var normal = normalsSource[index];
  29985. // Get two vectors perpendicular to the face normal and to each other.
  29986. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29987. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29988. // Six indices (two triangles) per face.
  29989. var verticesLength = positions.length / 3;
  29990. indices.push(verticesLength);
  29991. indices.push(verticesLength + 1);
  29992. indices.push(verticesLength + 2);
  29993. indices.push(verticesLength);
  29994. indices.push(verticesLength + 2);
  29995. indices.push(verticesLength + 3);
  29996. // Four vertices per face.
  29997. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29998. positions.push(vertex.x, vertex.y, vertex.z);
  29999. normals.push(normal.x, normal.y, normal.z);
  30000. uvs.push(faceUV[index].z, faceUV[index].w);
  30001. if (faceColors) {
  30002. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30003. }
  30004. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30005. positions.push(vertex.x, vertex.y, vertex.z);
  30006. normals.push(normal.x, normal.y, normal.z);
  30007. uvs.push(faceUV[index].x, faceUV[index].w);
  30008. if (faceColors) {
  30009. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30010. }
  30011. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30012. positions.push(vertex.x, vertex.y, vertex.z);
  30013. normals.push(normal.x, normal.y, normal.z);
  30014. uvs.push(faceUV[index].x, faceUV[index].y);
  30015. if (faceColors) {
  30016. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30017. }
  30018. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30019. positions.push(vertex.x, vertex.y, vertex.z);
  30020. normals.push(normal.x, normal.y, normal.z);
  30021. uvs.push(faceUV[index].z, faceUV[index].y);
  30022. if (faceColors) {
  30023. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30024. }
  30025. }
  30026. // sides
  30027. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30028. // Result
  30029. var vertexData = new VertexData();
  30030. vertexData.indices = indices;
  30031. vertexData.positions = positions;
  30032. vertexData.normals = normals;
  30033. vertexData.uvs = uvs;
  30034. if (faceColors) {
  30035. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30036. vertexData.colors = totalColors;
  30037. }
  30038. return vertexData;
  30039. };
  30040. /**
  30041. * Creates the VertexData of the Sphere.
  30042. */
  30043. VertexData.CreateSphere = function (options) {
  30044. var segments = options.segments || 32;
  30045. var diameterX = options.diameterX || options.diameter || 1;
  30046. var diameterY = options.diameterY || options.diameter || 1;
  30047. var diameterZ = options.diameterZ || options.diameter || 1;
  30048. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30049. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30050. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30051. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30052. var totalZRotationSteps = 2 + segments;
  30053. var totalYRotationSteps = 2 * totalZRotationSteps;
  30054. var indices = [];
  30055. var positions = [];
  30056. var normals = [];
  30057. var uvs = [];
  30058. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30059. var normalizedZ = zRotationStep / totalZRotationSteps;
  30060. var angleZ = normalizedZ * Math.PI * slice;
  30061. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30062. var normalizedY = yRotationStep / totalYRotationSteps;
  30063. var angleY = normalizedY * Math.PI * 2 * arc;
  30064. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30065. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30066. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30067. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30068. var vertex = complete.multiply(radius);
  30069. var normal = complete.divide(radius).normalize();
  30070. positions.push(vertex.x, vertex.y, vertex.z);
  30071. normals.push(normal.x, normal.y, normal.z);
  30072. uvs.push(normalizedY, normalizedZ);
  30073. }
  30074. if (zRotationStep > 0) {
  30075. var verticesCount = positions.length / 3;
  30076. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30077. indices.push((firstIndex));
  30078. indices.push((firstIndex + 1));
  30079. indices.push(firstIndex + totalYRotationSteps + 1);
  30080. indices.push((firstIndex + totalYRotationSteps + 1));
  30081. indices.push((firstIndex + 1));
  30082. indices.push((firstIndex + totalYRotationSteps + 2));
  30083. }
  30084. }
  30085. }
  30086. // Sides
  30087. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30088. // Result
  30089. var vertexData = new VertexData();
  30090. vertexData.indices = indices;
  30091. vertexData.positions = positions;
  30092. vertexData.normals = normals;
  30093. vertexData.uvs = uvs;
  30094. return vertexData;
  30095. };
  30096. /**
  30097. * Creates the VertexData of the Cylinder or Cone.
  30098. */
  30099. VertexData.CreateCylinder = function (options) {
  30100. var height = options.height || 2;
  30101. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30102. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30103. var tessellation = options.tessellation || 24;
  30104. var subdivisions = options.subdivisions || 1;
  30105. var hasRings = options.hasRings ? true : false;
  30106. var enclose = options.enclose ? true : false;
  30107. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30108. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30109. var faceUV = options.faceUV || new Array(3);
  30110. var faceColors = options.faceColors;
  30111. // default face colors and UV if undefined
  30112. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30113. var ringNb = (hasRings) ? subdivisions : 1;
  30114. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30115. var f;
  30116. for (f = 0; f < surfaceNb; f++) {
  30117. if (faceColors && faceColors[f] === undefined) {
  30118. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30119. }
  30120. }
  30121. for (f = 0; f < surfaceNb; f++) {
  30122. if (faceUV && faceUV[f] === undefined) {
  30123. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30124. }
  30125. }
  30126. var indices = new Array();
  30127. var positions = new Array();
  30128. var normals = new Array();
  30129. var uvs = new Array();
  30130. var colors = new Array();
  30131. var angle_step = Math.PI * 2 * arc / tessellation;
  30132. var angle;
  30133. var h;
  30134. var radius;
  30135. var tan = (diameterBottom - diameterTop) / 2 / height;
  30136. var ringVertex = BABYLON.Vector3.Zero();
  30137. var ringNormal = BABYLON.Vector3.Zero();
  30138. var ringFirstVertex = BABYLON.Vector3.Zero();
  30139. var ringFirstNormal = BABYLON.Vector3.Zero();
  30140. var quadNormal = BABYLON.Vector3.Zero();
  30141. var Y = BABYLON.Axis.Y;
  30142. // positions, normals, uvs
  30143. var i;
  30144. var j;
  30145. var r;
  30146. var ringIdx = 1;
  30147. var s = 1; // surface index
  30148. var cs = 0;
  30149. var v = 0;
  30150. for (i = 0; i <= subdivisions; i++) {
  30151. h = i / subdivisions;
  30152. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30153. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30154. for (r = 0; r < ringIdx; r++) {
  30155. if (hasRings) {
  30156. s += r;
  30157. }
  30158. if (enclose) {
  30159. s += 2 * r;
  30160. }
  30161. for (j = 0; j <= tessellation; j++) {
  30162. angle = j * angle_step;
  30163. // position
  30164. ringVertex.x = Math.cos(-angle) * radius;
  30165. ringVertex.y = -height / 2 + h * height;
  30166. ringVertex.z = Math.sin(-angle) * radius;
  30167. // normal
  30168. if (diameterTop === 0 && i === subdivisions) {
  30169. // if no top cap, reuse former normals
  30170. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30171. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30172. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30173. }
  30174. else {
  30175. ringNormal.x = ringVertex.x;
  30176. ringNormal.z = ringVertex.z;
  30177. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30178. ringNormal.normalize();
  30179. }
  30180. // keep first ring vertex values for enclose
  30181. if (j === 0) {
  30182. ringFirstVertex.copyFrom(ringVertex);
  30183. ringFirstNormal.copyFrom(ringNormal);
  30184. }
  30185. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30186. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30187. if (hasRings) {
  30188. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30189. }
  30190. else {
  30191. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30192. }
  30193. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30194. if (faceColors) {
  30195. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30196. }
  30197. }
  30198. // if enclose, add four vertices and their dedicated normals
  30199. if (arc !== 1 && enclose) {
  30200. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30201. positions.push(0, ringVertex.y, 0);
  30202. positions.push(0, ringVertex.y, 0);
  30203. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30204. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30205. quadNormal.normalize();
  30206. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30207. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30208. quadNormal.normalize();
  30209. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30210. if (hasRings) {
  30211. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30212. }
  30213. else {
  30214. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30215. }
  30216. uvs.push(faceUV[s + 1].x, v);
  30217. uvs.push(faceUV[s + 1].z, v);
  30218. if (hasRings) {
  30219. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30220. }
  30221. else {
  30222. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30223. }
  30224. uvs.push(faceUV[s + 2].x, v);
  30225. uvs.push(faceUV[s + 2].z, v);
  30226. if (faceColors) {
  30227. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30228. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30229. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30230. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30231. }
  30232. }
  30233. if (cs !== s) {
  30234. cs = s;
  30235. }
  30236. }
  30237. }
  30238. // indices
  30239. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30240. var s;
  30241. i = 0;
  30242. for (s = 0; s < subdivisions; s++) {
  30243. var i0 = 0;
  30244. var i1 = 0;
  30245. var i2 = 0;
  30246. var i3 = 0;
  30247. for (j = 0; j < tessellation; j++) {
  30248. i0 = i * (e + 1) + j;
  30249. i1 = (i + 1) * (e + 1) + j;
  30250. i2 = i * (e + 1) + (j + 1);
  30251. i3 = (i + 1) * (e + 1) + (j + 1);
  30252. indices.push(i0, i1, i2);
  30253. indices.push(i3, i2, i1);
  30254. }
  30255. if (arc !== 1 && enclose) {
  30256. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30257. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30258. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30259. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30260. }
  30261. i = (hasRings) ? (i + 2) : (i + 1);
  30262. }
  30263. // Caps
  30264. var createCylinderCap = function (isTop) {
  30265. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30266. if (radius === 0) {
  30267. return;
  30268. }
  30269. // Cap positions, normals & uvs
  30270. var angle;
  30271. var circleVector;
  30272. var i;
  30273. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30274. var c = null;
  30275. if (faceColors) {
  30276. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30277. }
  30278. // cap center
  30279. var vbase = positions.length / 3;
  30280. var offset = isTop ? height / 2 : -height / 2;
  30281. var center = new BABYLON.Vector3(0, offset, 0);
  30282. positions.push(center.x, center.y, center.z);
  30283. normals.push(0, isTop ? 1 : -1, 0);
  30284. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30285. if (c) {
  30286. colors.push(c.r, c.g, c.b, c.a);
  30287. }
  30288. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30289. for (i = 0; i <= tessellation; i++) {
  30290. angle = Math.PI * 2 * i * arc / tessellation;
  30291. var cos = Math.cos(-angle);
  30292. var sin = Math.sin(-angle);
  30293. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30294. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30295. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30296. normals.push(0, isTop ? 1 : -1, 0);
  30297. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30298. if (c) {
  30299. colors.push(c.r, c.g, c.b, c.a);
  30300. }
  30301. }
  30302. // Cap indices
  30303. for (i = 0; i < tessellation; i++) {
  30304. if (!isTop) {
  30305. indices.push(vbase);
  30306. indices.push(vbase + (i + 1));
  30307. indices.push(vbase + (i + 2));
  30308. }
  30309. else {
  30310. indices.push(vbase);
  30311. indices.push(vbase + (i + 2));
  30312. indices.push(vbase + (i + 1));
  30313. }
  30314. }
  30315. };
  30316. // add caps to geometry
  30317. createCylinderCap(false);
  30318. createCylinderCap(true);
  30319. // Sides
  30320. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30321. var vertexData = new VertexData();
  30322. vertexData.indices = indices;
  30323. vertexData.positions = positions;
  30324. vertexData.normals = normals;
  30325. vertexData.uvs = uvs;
  30326. if (faceColors) {
  30327. vertexData.colors = colors;
  30328. }
  30329. return vertexData;
  30330. };
  30331. /**
  30332. * Creates the VertexData of the Torus.
  30333. */
  30334. VertexData.CreateTorus = function (options) {
  30335. var indices = [];
  30336. var positions = [];
  30337. var normals = [];
  30338. var uvs = [];
  30339. var diameter = options.diameter || 1;
  30340. var thickness = options.thickness || 0.5;
  30341. var tessellation = options.tessellation || 16;
  30342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30343. var stride = tessellation + 1;
  30344. for (var i = 0; i <= tessellation; i++) {
  30345. var u = i / tessellation;
  30346. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30347. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30348. for (var j = 0; j <= tessellation; j++) {
  30349. var v = 1 - j / tessellation;
  30350. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30351. var dx = Math.cos(innerAngle);
  30352. var dy = Math.sin(innerAngle);
  30353. // Create a vertex.
  30354. var normal = new BABYLON.Vector3(dx, dy, 0);
  30355. var position = normal.scale(thickness / 2);
  30356. var textureCoordinate = new BABYLON.Vector2(u, v);
  30357. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30358. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30359. positions.push(position.x, position.y, position.z);
  30360. normals.push(normal.x, normal.y, normal.z);
  30361. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30362. // And create indices for two triangles.
  30363. var nextI = (i + 1) % stride;
  30364. var nextJ = (j + 1) % stride;
  30365. indices.push(i * stride + j);
  30366. indices.push(i * stride + nextJ);
  30367. indices.push(nextI * stride + j);
  30368. indices.push(i * stride + nextJ);
  30369. indices.push(nextI * stride + nextJ);
  30370. indices.push(nextI * stride + j);
  30371. }
  30372. }
  30373. // Sides
  30374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30375. // Result
  30376. var vertexData = new VertexData();
  30377. vertexData.indices = indices;
  30378. vertexData.positions = positions;
  30379. vertexData.normals = normals;
  30380. vertexData.uvs = uvs;
  30381. return vertexData;
  30382. };
  30383. /**
  30384. * Creates the VertexData of the LineSystem.
  30385. */
  30386. VertexData.CreateLineSystem = function (options) {
  30387. var indices = [];
  30388. var positions = [];
  30389. var lines = options.lines;
  30390. var colors = options.colors;
  30391. var vertexColors = [];
  30392. var idx = 0;
  30393. for (var l = 0; l < lines.length; l++) {
  30394. var points = lines[l];
  30395. for (var index = 0; index < points.length; index++) {
  30396. positions.push(points[index].x, points[index].y, points[index].z);
  30397. if (colors) {
  30398. var color = colors[l];
  30399. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30400. }
  30401. if (index > 0) {
  30402. indices.push(idx - 1);
  30403. indices.push(idx);
  30404. }
  30405. idx++;
  30406. }
  30407. }
  30408. var vertexData = new VertexData();
  30409. vertexData.indices = indices;
  30410. vertexData.positions = positions;
  30411. if (colors) {
  30412. vertexData.colors = vertexColors;
  30413. }
  30414. return vertexData;
  30415. };
  30416. /**
  30417. * Create the VertexData of the DashedLines.
  30418. */
  30419. VertexData.CreateDashedLines = function (options) {
  30420. var dashSize = options.dashSize || 3;
  30421. var gapSize = options.gapSize || 1;
  30422. var dashNb = options.dashNb || 200;
  30423. var points = options.points;
  30424. var positions = new Array();
  30425. var indices = new Array();
  30426. var curvect = BABYLON.Vector3.Zero();
  30427. var lg = 0;
  30428. var nb = 0;
  30429. var shft = 0;
  30430. var dashshft = 0;
  30431. var curshft = 0;
  30432. var idx = 0;
  30433. var i = 0;
  30434. for (i = 0; i < points.length - 1; i++) {
  30435. points[i + 1].subtractToRef(points[i], curvect);
  30436. lg += curvect.length();
  30437. }
  30438. shft = lg / dashNb;
  30439. dashshft = dashSize * shft / (dashSize + gapSize);
  30440. for (i = 0; i < points.length - 1; i++) {
  30441. points[i + 1].subtractToRef(points[i], curvect);
  30442. nb = Math.floor(curvect.length() / shft);
  30443. curvect.normalize();
  30444. for (var j = 0; j < nb; j++) {
  30445. curshft = shft * j;
  30446. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30447. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30448. indices.push(idx, idx + 1);
  30449. idx += 2;
  30450. }
  30451. }
  30452. // Result
  30453. var vertexData = new VertexData();
  30454. vertexData.positions = positions;
  30455. vertexData.indices = indices;
  30456. return vertexData;
  30457. };
  30458. /**
  30459. * Creates the VertexData of the Ground.
  30460. */
  30461. VertexData.CreateGround = function (options) {
  30462. var indices = [];
  30463. var positions = [];
  30464. var normals = [];
  30465. var uvs = [];
  30466. var row, col;
  30467. var width = options.width || 1;
  30468. var height = options.height || 1;
  30469. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30470. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30471. for (row = 0; row <= subdivisionsY; row++) {
  30472. for (col = 0; col <= subdivisionsX; col++) {
  30473. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30474. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30475. positions.push(position.x, position.y, position.z);
  30476. normals.push(normal.x, normal.y, normal.z);
  30477. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30478. }
  30479. }
  30480. for (row = 0; row < subdivisionsY; row++) {
  30481. for (col = 0; col < subdivisionsX; col++) {
  30482. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30483. indices.push(col + 1 + row * (subdivisionsX + 1));
  30484. indices.push(col + row * (subdivisionsX + 1));
  30485. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30486. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30487. indices.push(col + row * (subdivisionsX + 1));
  30488. }
  30489. }
  30490. // Result
  30491. var vertexData = new VertexData();
  30492. vertexData.indices = indices;
  30493. vertexData.positions = positions;
  30494. vertexData.normals = normals;
  30495. vertexData.uvs = uvs;
  30496. return vertexData;
  30497. };
  30498. /**
  30499. * Creates the VertexData of the TiledGround.
  30500. */
  30501. VertexData.CreateTiledGround = function (options) {
  30502. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30503. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30504. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30505. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30506. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30507. var precision = options.precision || { w: 1, h: 1 };
  30508. var indices = new Array();
  30509. var positions = new Array();
  30510. var normals = new Array();
  30511. var uvs = new Array();
  30512. var row, col, tileRow, tileCol;
  30513. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30514. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30515. precision.w = (precision.w < 1) ? 1 : precision.w;
  30516. precision.h = (precision.h < 1) ? 1 : precision.h;
  30517. var tileSize = {
  30518. 'w': (xmax - xmin) / subdivisions.w,
  30519. 'h': (zmax - zmin) / subdivisions.h
  30520. };
  30521. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30522. // Indices
  30523. var base = positions.length / 3;
  30524. var rowLength = precision.w + 1;
  30525. for (row = 0; row < precision.h; row++) {
  30526. for (col = 0; col < precision.w; col++) {
  30527. var square = [
  30528. base + col + row * rowLength,
  30529. base + (col + 1) + row * rowLength,
  30530. base + (col + 1) + (row + 1) * rowLength,
  30531. base + col + (row + 1) * rowLength
  30532. ];
  30533. indices.push(square[1]);
  30534. indices.push(square[2]);
  30535. indices.push(square[3]);
  30536. indices.push(square[0]);
  30537. indices.push(square[1]);
  30538. indices.push(square[3]);
  30539. }
  30540. }
  30541. // Position, normals and uvs
  30542. var position = BABYLON.Vector3.Zero();
  30543. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30544. for (row = 0; row <= precision.h; row++) {
  30545. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30546. for (col = 0; col <= precision.w; col++) {
  30547. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30548. position.y = 0;
  30549. positions.push(position.x, position.y, position.z);
  30550. normals.push(normal.x, normal.y, normal.z);
  30551. uvs.push(col / precision.w, row / precision.h);
  30552. }
  30553. }
  30554. }
  30555. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30556. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30557. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30558. }
  30559. }
  30560. // Result
  30561. var vertexData = new VertexData();
  30562. vertexData.indices = indices;
  30563. vertexData.positions = positions;
  30564. vertexData.normals = normals;
  30565. vertexData.uvs = uvs;
  30566. return vertexData;
  30567. };
  30568. /**
  30569. * Creates the VertexData of the Ground designed from a heightmap.
  30570. */
  30571. VertexData.CreateGroundFromHeightMap = function (options) {
  30572. var indices = [];
  30573. var positions = [];
  30574. var normals = [];
  30575. var uvs = [];
  30576. var row, col;
  30577. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30578. // Vertices
  30579. for (row = 0; row <= options.subdivisions; row++) {
  30580. for (col = 0; col <= options.subdivisions; col++) {
  30581. 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));
  30582. // Compute height
  30583. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30584. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30585. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30586. var r = options.buffer[pos] / 255.0;
  30587. var g = options.buffer[pos + 1] / 255.0;
  30588. var b = options.buffer[pos + 2] / 255.0;
  30589. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30590. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30591. // Add vertex
  30592. positions.push(position.x, position.y, position.z);
  30593. normals.push(0, 0, 0);
  30594. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30595. }
  30596. }
  30597. // Indices
  30598. for (row = 0; row < options.subdivisions; row++) {
  30599. for (col = 0; col < options.subdivisions; col++) {
  30600. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30601. indices.push(col + 1 + row * (options.subdivisions + 1));
  30602. indices.push(col + row * (options.subdivisions + 1));
  30603. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30604. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30605. indices.push(col + row * (options.subdivisions + 1));
  30606. }
  30607. }
  30608. // Normals
  30609. VertexData.ComputeNormals(positions, indices, normals);
  30610. // Result
  30611. var vertexData = new VertexData();
  30612. vertexData.indices = indices;
  30613. vertexData.positions = positions;
  30614. vertexData.normals = normals;
  30615. vertexData.uvs = uvs;
  30616. return vertexData;
  30617. };
  30618. /**
  30619. * Creates the VertexData of the Plane.
  30620. */
  30621. VertexData.CreatePlane = function (options) {
  30622. var indices = [];
  30623. var positions = [];
  30624. var normals = [];
  30625. var uvs = [];
  30626. var width = options.width || options.size || 1;
  30627. var height = options.height || options.size || 1;
  30628. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30629. // Vertices
  30630. var halfWidth = width / 2.0;
  30631. var halfHeight = height / 2.0;
  30632. positions.push(-halfWidth, -halfHeight, 0);
  30633. normals.push(0, 0, -1.0);
  30634. uvs.push(0.0, 0.0);
  30635. positions.push(halfWidth, -halfHeight, 0);
  30636. normals.push(0, 0, -1.0);
  30637. uvs.push(1.0, 0.0);
  30638. positions.push(halfWidth, halfHeight, 0);
  30639. normals.push(0, 0, -1.0);
  30640. uvs.push(1.0, 1.0);
  30641. positions.push(-halfWidth, halfHeight, 0);
  30642. normals.push(0, 0, -1.0);
  30643. uvs.push(0.0, 1.0);
  30644. // Indices
  30645. indices.push(0);
  30646. indices.push(1);
  30647. indices.push(2);
  30648. indices.push(0);
  30649. indices.push(2);
  30650. indices.push(3);
  30651. // Sides
  30652. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30653. // Result
  30654. var vertexData = new VertexData();
  30655. vertexData.indices = indices;
  30656. vertexData.positions = positions;
  30657. vertexData.normals = normals;
  30658. vertexData.uvs = uvs;
  30659. return vertexData;
  30660. };
  30661. /**
  30662. * Creates the VertexData of the Disc or regular Polygon.
  30663. */
  30664. VertexData.CreateDisc = function (options) {
  30665. var positions = new Array();
  30666. var indices = new Array();
  30667. var normals = new Array();
  30668. var uvs = new Array();
  30669. var radius = options.radius || 0.5;
  30670. var tessellation = options.tessellation || 64;
  30671. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30672. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30673. // positions and uvs
  30674. positions.push(0, 0, 0); // disc center first
  30675. uvs.push(0.5, 0.5);
  30676. var theta = Math.PI * 2 * arc;
  30677. var step = theta / tessellation;
  30678. for (var a = 0; a < theta; a += step) {
  30679. var x = Math.cos(a);
  30680. var y = Math.sin(a);
  30681. var u = (x + 1) / 2;
  30682. var v = (1 - y) / 2;
  30683. positions.push(radius * x, radius * y, 0);
  30684. uvs.push(u, v);
  30685. }
  30686. if (arc === 1) {
  30687. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30688. uvs.push(uvs[2], uvs[3]);
  30689. }
  30690. //indices
  30691. var vertexNb = positions.length / 3;
  30692. for (var i = 1; i < vertexNb - 1; i++) {
  30693. indices.push(i + 1, 0, i);
  30694. }
  30695. // result
  30696. VertexData.ComputeNormals(positions, indices, normals);
  30697. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30698. var vertexData = new VertexData();
  30699. vertexData.indices = indices;
  30700. vertexData.positions = positions;
  30701. vertexData.normals = normals;
  30702. vertexData.uvs = uvs;
  30703. return vertexData;
  30704. };
  30705. /**
  30706. * Re-creates the VertexData of the Polygon for sideOrientation.
  30707. */
  30708. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30709. var faceUV = fUV || new Array(3);
  30710. var faceColors = fColors;
  30711. var colors = [];
  30712. // default face colors and UV if undefined
  30713. for (var f = 0; f < 3; f++) {
  30714. if (faceUV[f] === undefined) {
  30715. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30716. }
  30717. if (faceColors && faceColors[f] === undefined) {
  30718. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30719. }
  30720. }
  30721. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30722. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30723. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30724. var indices = polygon.getIndices();
  30725. // set face colours and textures
  30726. var idx = 0;
  30727. var face = 0;
  30728. for (var index = 0; index < normals.length; index += 3) {
  30729. //Edge Face no. 1
  30730. if (Math.abs(normals[index + 1]) < 0.001) {
  30731. face = 1;
  30732. }
  30733. //Top Face no. 0
  30734. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30735. face = 0;
  30736. }
  30737. //Bottom Face no. 2
  30738. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30739. face = 2;
  30740. }
  30741. idx = index / 3;
  30742. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30743. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30744. if (faceColors) {
  30745. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30746. }
  30747. }
  30748. // sides
  30749. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30750. // Result
  30751. var vertexData = new VertexData();
  30752. vertexData.indices = indices;
  30753. vertexData.positions = positions;
  30754. vertexData.normals = normals;
  30755. vertexData.uvs = uvs;
  30756. if (faceColors) {
  30757. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30758. vertexData.colors = totalColors;
  30759. }
  30760. return vertexData;
  30761. };
  30762. /**
  30763. * Creates the VertexData of the IcoSphere.
  30764. */
  30765. VertexData.CreateIcoSphere = function (options) {
  30766. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30767. var radius = options.radius || 1;
  30768. var flat = (options.flat === undefined) ? true : options.flat;
  30769. var subdivisions = options.subdivisions || 4;
  30770. var radiusX = options.radiusX || radius;
  30771. var radiusY = options.radiusY || radius;
  30772. var radiusZ = options.radiusZ || radius;
  30773. var t = (1 + Math.sqrt(5)) / 2;
  30774. // 12 vertex x,y,z
  30775. var ico_vertices = [
  30776. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30777. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30778. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30779. ];
  30780. // index of 3 vertex makes a face of icopshere
  30781. var ico_indices = [
  30782. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30783. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30784. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30785. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30786. ];
  30787. // vertex for uv have aliased position, not for UV
  30788. var vertices_unalias_id = [
  30789. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30790. // vertex alias
  30791. 0,
  30792. 2,
  30793. 3,
  30794. 3,
  30795. 3,
  30796. 4,
  30797. 7,
  30798. 8,
  30799. 9,
  30800. 9,
  30801. 10,
  30802. 11 // 23: B + 12
  30803. ];
  30804. // uv as integer step (not pixels !)
  30805. var ico_vertexuv = [
  30806. 5, 1, 3, 1, 6, 4, 0, 0,
  30807. 5, 3, 4, 2, 2, 2, 4, 0,
  30808. 2, 0, 1, 1, 6, 0, 6, 2,
  30809. // vertex alias (for same vertex on different faces)
  30810. 0, 4,
  30811. 3, 3,
  30812. 4, 4,
  30813. 3, 1,
  30814. 4, 2,
  30815. 4, 4,
  30816. 0, 2,
  30817. 1, 1,
  30818. 2, 2,
  30819. 3, 3,
  30820. 1, 3,
  30821. 2, 4 // 23: B + 12
  30822. ];
  30823. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30824. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30825. // First island of uv mapping
  30826. // v = 4h 3+ 2
  30827. // v = 3h 9+ 4
  30828. // v = 2h 9+ 5 B
  30829. // v = 1h 9 1 0
  30830. // v = 0h 3 8 7 A
  30831. // u = 0 1 2 3 4 5 6 *a
  30832. // Second island of uv mapping
  30833. // v = 4h 0+ B+ 4+
  30834. // v = 3h A+ 2+
  30835. // v = 2h 7+ 6 3+
  30836. // v = 1h 8+ 3+
  30837. // v = 0h
  30838. // u = 0 1 2 3 4 5 6 *a
  30839. // Face layout on texture UV mapping
  30840. // ============
  30841. // \ 4 /\ 16 / ======
  30842. // \ / \ / /\ 11 /
  30843. // \/ 7 \/ / \ /
  30844. // ======= / 10 \/
  30845. // /\ 17 /\ =======
  30846. // / \ / \ \ 15 /\
  30847. // / 8 \/ 12 \ \ / \
  30848. // ============ \/ 6 \
  30849. // \ 18 /\ ============
  30850. // \ / \ \ 5 /\ 0 /
  30851. // \/ 13 \ \ / \ /
  30852. // ======= \/ 1 \/
  30853. // =============
  30854. // /\ 19 /\ 2 /\
  30855. // / \ / \ / \
  30856. // / 14 \/ 9 \/ 3 \
  30857. // ===================
  30858. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30859. var ustep = 138 / 1024;
  30860. var vstep = 239 / 1024;
  30861. var uoffset = 60 / 1024;
  30862. var voffset = 26 / 1024;
  30863. // Second island should have margin, not to touch the first island
  30864. // avoid any borderline artefact in pixel rounding
  30865. var island_u_offset = -40 / 1024;
  30866. var island_v_offset = +20 / 1024;
  30867. // face is either island 0 or 1 :
  30868. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30869. var island = [
  30870. 0, 0, 0, 0, 1,
  30871. 0, 0, 1, 1, 0,
  30872. 0, 0, 1, 1, 0,
  30873. 0, 1, 1, 1, 0 // 15 - 19
  30874. ];
  30875. var indices = new Array();
  30876. var positions = new Array();
  30877. var normals = new Array();
  30878. var uvs = new Array();
  30879. var current_indice = 0;
  30880. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30881. var face_vertex_pos = new Array(3);
  30882. var face_vertex_uv = new Array(3);
  30883. var v012;
  30884. for (v012 = 0; v012 < 3; v012++) {
  30885. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30886. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30887. }
  30888. // create all with normals
  30889. for (var face = 0; face < 20; face++) {
  30890. // 3 vertex per face
  30891. for (v012 = 0; v012 < 3; v012++) {
  30892. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30893. var v_id = ico_indices[3 * face + v012];
  30894. // vertex have 3D position (x,y,z)
  30895. 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]);
  30896. // Normalize to get normal, then scale to radius
  30897. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30898. // uv Coordinates from vertex ID
  30899. 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);
  30900. }
  30901. // Subdivide the face (interpolate pos, norm, uv)
  30902. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30903. // - norm is linear interpolation of vertex corner normal
  30904. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30905. // - uv is linear interpolation
  30906. //
  30907. // Topology is as below for sub-divide by 2
  30908. // vertex shown as v0,v1,v2
  30909. // interp index is i1 to progress in range [v0,v1[
  30910. // interp index is i2 to progress in range [v0,v2[
  30911. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30912. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30913. //
  30914. //
  30915. // i2 v2
  30916. // ^ ^
  30917. // / / \
  30918. // / / \
  30919. // / / \
  30920. // / / (0,1) \
  30921. // / #---------\
  30922. // / / \ (0,0)'/ \
  30923. // / / \ / \
  30924. // / / \ / \
  30925. // / / (0,0) \ / (1,0) \
  30926. // / #---------#---------\
  30927. // v0 v1
  30928. //
  30929. // --------------------> i1
  30930. //
  30931. // interp of (i1,i2):
  30932. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30933. // along i1 : lerp(x0,x1, i1/(S-i2))
  30934. //
  30935. // centroid of triangle is needed to get help normal computation
  30936. // (c1,c2) are used for centroid location
  30937. var interp_vertex = function (i1, i2, c1, c2) {
  30938. // vertex is interpolated from
  30939. // - face_vertex_pos[0..2]
  30940. // - face_vertex_uv[0..2]
  30941. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30942. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30943. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30944. pos_interp.normalize();
  30945. var vertex_normal;
  30946. if (flat) {
  30947. // in flat mode, recalculate normal as face centroid normal
  30948. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30949. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30950. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30951. }
  30952. else {
  30953. // in smooth mode, recalculate normal from each single vertex position
  30954. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30955. }
  30956. // Vertex normal need correction due to X,Y,Z radius scaling
  30957. vertex_normal.x /= radiusX;
  30958. vertex_normal.y /= radiusY;
  30959. vertex_normal.z /= radiusZ;
  30960. vertex_normal.normalize();
  30961. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30962. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30963. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30964. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30965. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30966. uvs.push(uv_interp.x, uv_interp.y);
  30967. // push each vertex has member of a face
  30968. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30969. indices.push(current_indice);
  30970. current_indice++;
  30971. };
  30972. for (var i2 = 0; i2 < subdivisions; i2++) {
  30973. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30974. // face : (i1,i2) for /\ :
  30975. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30976. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30977. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30978. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30979. if (i1 + i2 + 1 < subdivisions) {
  30980. // face : (i1,i2)' for \/ :
  30981. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30982. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30983. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30984. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30985. }
  30986. }
  30987. }
  30988. }
  30989. // Sides
  30990. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30991. // Result
  30992. var vertexData = new VertexData();
  30993. vertexData.indices = indices;
  30994. vertexData.positions = positions;
  30995. vertexData.normals = normals;
  30996. vertexData.uvs = uvs;
  30997. return vertexData;
  30998. };
  30999. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31000. /**
  31001. * Creates the VertexData of the Polyhedron.
  31002. */
  31003. VertexData.CreatePolyhedron = function (options) {
  31004. // provided polyhedron types :
  31005. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31006. // 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)
  31007. var polyhedra = [];
  31008. 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]] };
  31009. 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]] };
  31010. polyhedra[2] = {
  31011. 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]],
  31012. 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]]
  31013. };
  31014. polyhedra[3] = {
  31015. 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]],
  31016. 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]]
  31017. };
  31018. polyhedra[4] = {
  31019. 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]],
  31020. 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]]
  31021. };
  31022. 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]] };
  31023. 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]] };
  31024. 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]] };
  31025. 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]] };
  31026. 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]] };
  31027. 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]] };
  31028. 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]] };
  31029. 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]] };
  31030. 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]] };
  31031. polyhedra[14] = {
  31032. 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]],
  31033. 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]]
  31034. };
  31035. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31036. var size = options.size;
  31037. var sizeX = options.sizeX || size || 1;
  31038. var sizeY = options.sizeY || size || 1;
  31039. var sizeZ = options.sizeZ || size || 1;
  31040. var data = options.custom || polyhedra[type];
  31041. var nbfaces = data.face.length;
  31042. var faceUV = options.faceUV || new Array(nbfaces);
  31043. var faceColors = options.faceColors;
  31044. var flat = (options.flat === undefined) ? true : options.flat;
  31045. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31046. var positions = new Array();
  31047. var indices = new Array();
  31048. var normals = new Array();
  31049. var uvs = new Array();
  31050. var colors = new Array();
  31051. var index = 0;
  31052. var faceIdx = 0; // face cursor in the array "indexes"
  31053. var indexes = new Array();
  31054. var i = 0;
  31055. var f = 0;
  31056. var u, v, ang, x, y, tmp;
  31057. // default face colors and UV if undefined
  31058. if (flat) {
  31059. for (f = 0; f < nbfaces; f++) {
  31060. if (faceColors && faceColors[f] === undefined) {
  31061. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31062. }
  31063. if (faceUV && faceUV[f] === undefined) {
  31064. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31065. }
  31066. }
  31067. }
  31068. if (!flat) {
  31069. for (i = 0; i < data.vertex.length; i++) {
  31070. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31071. uvs.push(0, 0);
  31072. }
  31073. for (f = 0; f < nbfaces; f++) {
  31074. for (i = 0; i < data.face[f].length - 2; i++) {
  31075. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31076. }
  31077. }
  31078. }
  31079. else {
  31080. for (f = 0; f < nbfaces; f++) {
  31081. var fl = data.face[f].length; // number of vertices of the current face
  31082. ang = 2 * Math.PI / fl;
  31083. x = 0.5 * Math.tan(ang / 2);
  31084. y = 0.5;
  31085. // positions, uvs, colors
  31086. for (i = 0; i < fl; i++) {
  31087. // positions
  31088. 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);
  31089. indexes.push(index);
  31090. index++;
  31091. // uvs
  31092. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31093. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31094. uvs.push(u, v);
  31095. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31096. y = x * Math.sin(ang) + y * Math.cos(ang);
  31097. x = tmp;
  31098. // colors
  31099. if (faceColors) {
  31100. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31101. }
  31102. }
  31103. // indices from indexes
  31104. for (i = 0; i < fl - 2; i++) {
  31105. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31106. }
  31107. faceIdx += fl;
  31108. }
  31109. }
  31110. VertexData.ComputeNormals(positions, indices, normals);
  31111. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31112. var vertexData = new VertexData();
  31113. vertexData.positions = positions;
  31114. vertexData.indices = indices;
  31115. vertexData.normals = normals;
  31116. vertexData.uvs = uvs;
  31117. if (faceColors && flat) {
  31118. vertexData.colors = colors;
  31119. }
  31120. return vertexData;
  31121. };
  31122. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31123. /**
  31124. * Creates the VertexData of the Torus Knot.
  31125. */
  31126. VertexData.CreateTorusKnot = function (options) {
  31127. var indices = new Array();
  31128. var positions = new Array();
  31129. var normals = new Array();
  31130. var uvs = new Array();
  31131. var radius = options.radius || 2;
  31132. var tube = options.tube || 0.5;
  31133. var radialSegments = options.radialSegments || 32;
  31134. var tubularSegments = options.tubularSegments || 32;
  31135. var p = options.p || 2;
  31136. var q = options.q || 3;
  31137. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31138. // Helper
  31139. var getPos = function (angle) {
  31140. var cu = Math.cos(angle);
  31141. var su = Math.sin(angle);
  31142. var quOverP = q / p * angle;
  31143. var cs = Math.cos(quOverP);
  31144. var tx = radius * (2 + cs) * 0.5 * cu;
  31145. var ty = radius * (2 + cs) * su * 0.5;
  31146. var tz = radius * Math.sin(quOverP) * 0.5;
  31147. return new BABYLON.Vector3(tx, ty, tz);
  31148. };
  31149. // Vertices
  31150. var i;
  31151. var j;
  31152. for (i = 0; i <= radialSegments; i++) {
  31153. var modI = i % radialSegments;
  31154. var u = modI / radialSegments * 2 * p * Math.PI;
  31155. var p1 = getPos(u);
  31156. var p2 = getPos(u + 0.01);
  31157. var tang = p2.subtract(p1);
  31158. var n = p2.add(p1);
  31159. var bitan = BABYLON.Vector3.Cross(tang, n);
  31160. n = BABYLON.Vector3.Cross(bitan, tang);
  31161. bitan.normalize();
  31162. n.normalize();
  31163. for (j = 0; j < tubularSegments; j++) {
  31164. var modJ = j % tubularSegments;
  31165. var v = modJ / tubularSegments * 2 * Math.PI;
  31166. var cx = -tube * Math.cos(v);
  31167. var cy = tube * Math.sin(v);
  31168. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31169. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31170. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31171. uvs.push(i / radialSegments);
  31172. uvs.push(j / tubularSegments);
  31173. }
  31174. }
  31175. for (i = 0; i < radialSegments; i++) {
  31176. for (j = 0; j < tubularSegments; j++) {
  31177. var jNext = (j + 1) % tubularSegments;
  31178. var a = i * tubularSegments + j;
  31179. var b = (i + 1) * tubularSegments + j;
  31180. var c = (i + 1) * tubularSegments + jNext;
  31181. var d = i * tubularSegments + jNext;
  31182. indices.push(d);
  31183. indices.push(b);
  31184. indices.push(a);
  31185. indices.push(d);
  31186. indices.push(c);
  31187. indices.push(b);
  31188. }
  31189. }
  31190. // Normals
  31191. VertexData.ComputeNormals(positions, indices, normals);
  31192. // Sides
  31193. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31194. // Result
  31195. var vertexData = new VertexData();
  31196. vertexData.indices = indices;
  31197. vertexData.positions = positions;
  31198. vertexData.normals = normals;
  31199. vertexData.uvs = uvs;
  31200. return vertexData;
  31201. };
  31202. // Tools
  31203. /**
  31204. * @param {any} - positions (number[] or Float32Array)
  31205. * @param {any} - indices (number[] or Uint16Array)
  31206. * @param {any} - normals (number[] or Float32Array)
  31207. * options (optional) :
  31208. * facetPositions : optional array of facet positions (vector3)
  31209. * facetNormals : optional array of facet normals (vector3)
  31210. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31211. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31212. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31213. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31214. * bInfo : optional bounding info, required for facetPartitioning computation
  31215. * useRightHandedSystem: optional boolean to for right handed system computation
  31216. * depthSort : optional boolean to enable the facet depth sort computation
  31217. * distanceTo : optional Vector3 to compute the facet depth from this location
  31218. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31219. */
  31220. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31221. // temporary scalar variables
  31222. var index = 0; // facet index
  31223. var p1p2x = 0.0; // p1p2 vector x coordinate
  31224. var p1p2y = 0.0; // p1p2 vector y coordinate
  31225. var p1p2z = 0.0; // p1p2 vector z coordinate
  31226. var p3p2x = 0.0; // p3p2 vector x coordinate
  31227. var p3p2y = 0.0; // p3p2 vector y coordinate
  31228. var p3p2z = 0.0; // p3p2 vector z coordinate
  31229. var faceNormalx = 0.0; // facet normal x coordinate
  31230. var faceNormaly = 0.0; // facet normal y coordinate
  31231. var faceNormalz = 0.0; // facet normal z coordinate
  31232. var length = 0.0; // facet normal length before normalization
  31233. var v1x = 0; // vector1 x index in the positions array
  31234. var v1y = 0; // vector1 y index in the positions array
  31235. var v1z = 0; // vector1 z index in the positions array
  31236. var v2x = 0; // vector2 x index in the positions array
  31237. var v2y = 0; // vector2 y index in the positions array
  31238. var v2z = 0; // vector2 z index in the positions array
  31239. var v3x = 0; // vector3 x index in the positions array
  31240. var v3y = 0; // vector3 y index in the positions array
  31241. var v3z = 0; // vector3 z index in the positions array
  31242. var computeFacetNormals = false;
  31243. var computeFacetPositions = false;
  31244. var computeFacetPartitioning = false;
  31245. var computeDepthSort = false;
  31246. var faceNormalSign = 1;
  31247. var ratio = 0;
  31248. var distanceTo = null;
  31249. if (options) {
  31250. computeFacetNormals = (options.facetNormals) ? true : false;
  31251. computeFacetPositions = (options.facetPositions) ? true : false;
  31252. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31253. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31254. ratio = options.ratio || 0;
  31255. computeDepthSort = (options.depthSort) ? true : false;
  31256. distanceTo = (options.distanceTo);
  31257. if (computeDepthSort) {
  31258. if (distanceTo === undefined) {
  31259. distanceTo = BABYLON.Vector3.Zero();
  31260. }
  31261. var depthSortedFacets = options.depthSortedFacets;
  31262. }
  31263. }
  31264. // facetPartitioning reinit if needed
  31265. var xSubRatio = 0;
  31266. var ySubRatio = 0;
  31267. var zSubRatio = 0;
  31268. var subSq = 0;
  31269. if (computeFacetPartitioning && options && options.bbSize) {
  31270. var ox = 0; // X partitioning index for facet position
  31271. var oy = 0; // Y partinioning index for facet position
  31272. var oz = 0; // Z partinioning index for facet position
  31273. var b1x = 0; // X partitioning index for facet v1 vertex
  31274. var b1y = 0; // Y partitioning index for facet v1 vertex
  31275. var b1z = 0; // z partitioning index for facet v1 vertex
  31276. var b2x = 0; // X partitioning index for facet v2 vertex
  31277. var b2y = 0; // Y partitioning index for facet v2 vertex
  31278. var b2z = 0; // Z partitioning index for facet v2 vertex
  31279. var b3x = 0; // X partitioning index for facet v3 vertex
  31280. var b3y = 0; // Y partitioning index for facet v3 vertex
  31281. var b3z = 0; // Z partitioning index for facet v3 vertex
  31282. var block_idx_o = 0; // facet barycenter block index
  31283. var block_idx_v1 = 0; // v1 vertex block index
  31284. var block_idx_v2 = 0; // v2 vertex block index
  31285. var block_idx_v3 = 0; // v3 vertex block index
  31286. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31287. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31288. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31289. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31290. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31291. subSq = options.subDiv.max * options.subDiv.max;
  31292. options.facetPartitioning.length = 0;
  31293. }
  31294. // reset the normals
  31295. for (index = 0; index < positions.length; index++) {
  31296. normals[index] = 0.0;
  31297. }
  31298. // Loop : 1 indice triplet = 1 facet
  31299. var nbFaces = (indices.length / 3) | 0;
  31300. for (index = 0; index < nbFaces; index++) {
  31301. // get the indexes of the coordinates of each vertex of the facet
  31302. v1x = indices[index * 3] * 3;
  31303. v1y = v1x + 1;
  31304. v1z = v1x + 2;
  31305. v2x = indices[index * 3 + 1] * 3;
  31306. v2y = v2x + 1;
  31307. v2z = v2x + 2;
  31308. v3x = indices[index * 3 + 2] * 3;
  31309. v3y = v3x + 1;
  31310. v3z = v3x + 2;
  31311. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31312. p1p2y = positions[v1y] - positions[v2y];
  31313. p1p2z = positions[v1z] - positions[v2z];
  31314. p3p2x = positions[v3x] - positions[v2x];
  31315. p3p2y = positions[v3y] - positions[v2y];
  31316. p3p2z = positions[v3z] - positions[v2z];
  31317. // compute the face normal with the cross product
  31318. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31319. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31320. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31321. // normalize this normal and store it in the array facetData
  31322. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31323. length = (length === 0) ? 1.0 : length;
  31324. faceNormalx /= length;
  31325. faceNormaly /= length;
  31326. faceNormalz /= length;
  31327. if (computeFacetNormals && options) {
  31328. options.facetNormals[index].x = faceNormalx;
  31329. options.facetNormals[index].y = faceNormaly;
  31330. options.facetNormals[index].z = faceNormalz;
  31331. }
  31332. if (computeFacetPositions && options) {
  31333. // compute and the facet barycenter coordinates in the array facetPositions
  31334. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31335. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31336. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31337. }
  31338. if (computeFacetPartitioning && options) {
  31339. // store the facet indexes in arrays in the main facetPartitioning array :
  31340. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31341. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31342. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31343. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31344. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31345. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31346. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31347. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31348. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31349. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31350. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31351. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31352. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31353. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31354. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31355. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31356. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31357. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31358. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31359. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31360. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31361. // push each facet index in each block containing the vertex
  31362. options.facetPartitioning[block_idx_v1].push(index);
  31363. if (block_idx_v2 != block_idx_v1) {
  31364. options.facetPartitioning[block_idx_v2].push(index);
  31365. }
  31366. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31367. options.facetPartitioning[block_idx_v3].push(index);
  31368. }
  31369. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31370. options.facetPartitioning[block_idx_o].push(index);
  31371. }
  31372. }
  31373. if (computeDepthSort && options && options.facetPositions) {
  31374. var dsf = depthSortedFacets[index];
  31375. dsf.ind = index * 3;
  31376. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31377. }
  31378. // compute the normals anyway
  31379. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31380. normals[v1y] += faceNormaly;
  31381. normals[v1z] += faceNormalz;
  31382. normals[v2x] += faceNormalx;
  31383. normals[v2y] += faceNormaly;
  31384. normals[v2z] += faceNormalz;
  31385. normals[v3x] += faceNormalx;
  31386. normals[v3y] += faceNormaly;
  31387. normals[v3z] += faceNormalz;
  31388. }
  31389. // last normalization of each normal
  31390. for (index = 0; index < normals.length / 3; index++) {
  31391. faceNormalx = normals[index * 3];
  31392. faceNormaly = normals[index * 3 + 1];
  31393. faceNormalz = normals[index * 3 + 2];
  31394. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31395. length = (length === 0) ? 1.0 : length;
  31396. faceNormalx /= length;
  31397. faceNormaly /= length;
  31398. faceNormalz /= length;
  31399. normals[index * 3] = faceNormalx;
  31400. normals[index * 3 + 1] = faceNormaly;
  31401. normals[index * 3 + 2] = faceNormalz;
  31402. }
  31403. };
  31404. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31405. var li = indices.length;
  31406. var ln = normals.length;
  31407. var i;
  31408. var n;
  31409. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31410. switch (sideOrientation) {
  31411. case BABYLON.Mesh.FRONTSIDE:
  31412. // nothing changed
  31413. break;
  31414. case BABYLON.Mesh.BACKSIDE:
  31415. var tmp;
  31416. // indices
  31417. for (i = 0; i < li; i += 3) {
  31418. tmp = indices[i];
  31419. indices[i] = indices[i + 2];
  31420. indices[i + 2] = tmp;
  31421. }
  31422. // normals
  31423. for (n = 0; n < ln; n++) {
  31424. normals[n] = -normals[n];
  31425. }
  31426. break;
  31427. case BABYLON.Mesh.DOUBLESIDE:
  31428. // positions
  31429. var lp = positions.length;
  31430. var l = lp / 3;
  31431. for (var p = 0; p < lp; p++) {
  31432. positions[lp + p] = positions[p];
  31433. }
  31434. // indices
  31435. for (i = 0; i < li; i += 3) {
  31436. indices[i + li] = indices[i + 2] + l;
  31437. indices[i + 1 + li] = indices[i + 1] + l;
  31438. indices[i + 2 + li] = indices[i] + l;
  31439. }
  31440. // normals
  31441. for (n = 0; n < ln; n++) {
  31442. normals[ln + n] = -normals[n];
  31443. }
  31444. // uvs
  31445. var lu = uvs.length;
  31446. var u = 0;
  31447. for (u = 0; u < lu; u++) {
  31448. uvs[u + lu] = uvs[u];
  31449. }
  31450. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31451. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31452. u = 0;
  31453. for (i = 0; i < lu / 2; i++) {
  31454. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31455. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31456. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31457. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31458. u += 2;
  31459. }
  31460. break;
  31461. }
  31462. };
  31463. /**
  31464. * Creates a new VertexData from the imported parameters.
  31465. */
  31466. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31467. var vertexData = new VertexData();
  31468. // positions
  31469. var positions = parsedVertexData.positions;
  31470. if (positions) {
  31471. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31472. }
  31473. // normals
  31474. var normals = parsedVertexData.normals;
  31475. if (normals) {
  31476. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31477. }
  31478. // tangents
  31479. var tangents = parsedVertexData.tangents;
  31480. if (tangents) {
  31481. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31482. }
  31483. // uvs
  31484. var uvs = parsedVertexData.uvs;
  31485. if (uvs) {
  31486. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31487. }
  31488. // uv2s
  31489. var uv2s = parsedVertexData.uv2s;
  31490. if (uv2s) {
  31491. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31492. }
  31493. // uv3s
  31494. var uv3s = parsedVertexData.uv3s;
  31495. if (uv3s) {
  31496. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31497. }
  31498. // uv4s
  31499. var uv4s = parsedVertexData.uv4s;
  31500. if (uv4s) {
  31501. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31502. }
  31503. // uv5s
  31504. var uv5s = parsedVertexData.uv5s;
  31505. if (uv5s) {
  31506. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31507. }
  31508. // uv6s
  31509. var uv6s = parsedVertexData.uv6s;
  31510. if (uv6s) {
  31511. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31512. }
  31513. // colors
  31514. var colors = parsedVertexData.colors;
  31515. if (colors) {
  31516. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31517. }
  31518. // matricesIndices
  31519. var matricesIndices = parsedVertexData.matricesIndices;
  31520. if (matricesIndices) {
  31521. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31522. }
  31523. // matricesWeights
  31524. var matricesWeights = parsedVertexData.matricesWeights;
  31525. if (matricesWeights) {
  31526. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31527. }
  31528. // indices
  31529. var indices = parsedVertexData.indices;
  31530. if (indices) {
  31531. vertexData.indices = indices;
  31532. }
  31533. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31534. };
  31535. return VertexData;
  31536. }());
  31537. BABYLON.VertexData = VertexData;
  31538. })(BABYLON || (BABYLON = {}));
  31539. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31540. var BABYLON;
  31541. (function (BABYLON) {
  31542. var Geometry = /** @class */ (function () {
  31543. function Geometry(id, scene, vertexData, updatable, mesh) {
  31544. if (updatable === void 0) { updatable = false; }
  31545. if (mesh === void 0) { mesh = null; }
  31546. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31547. this._totalVertices = 0;
  31548. this._isDisposed = false;
  31549. this._indexBufferIsUpdatable = false;
  31550. this.id = id;
  31551. this._engine = scene.getEngine();
  31552. this._meshes = [];
  31553. this._scene = scene;
  31554. //Init vertex buffer cache
  31555. this._vertexBuffers = {};
  31556. this._indices = [];
  31557. this._updatable = updatable;
  31558. // vertexData
  31559. if (vertexData) {
  31560. this.setAllVerticesData(vertexData, updatable);
  31561. }
  31562. else {
  31563. this._totalVertices = 0;
  31564. this._indices = [];
  31565. }
  31566. if (this._engine.getCaps().vertexArrayObject) {
  31567. this._vertexArrayObjects = {};
  31568. }
  31569. // applyToMesh
  31570. if (mesh) {
  31571. if (mesh.getClassName() === "LinesMesh") {
  31572. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31573. this.updateExtend();
  31574. }
  31575. this.applyToMesh(mesh);
  31576. mesh.computeWorldMatrix(true);
  31577. }
  31578. }
  31579. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31580. /**
  31581. * 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
  31582. * @returns The Bias Vector
  31583. */
  31584. get: function () {
  31585. return this._boundingBias;
  31586. },
  31587. set: function (value) {
  31588. if (this._boundingBias && this._boundingBias.equals(value)) {
  31589. return;
  31590. }
  31591. this._boundingBias = value.clone();
  31592. this.updateBoundingInfo(true, null);
  31593. },
  31594. enumerable: true,
  31595. configurable: true
  31596. });
  31597. Geometry.CreateGeometryForMesh = function (mesh) {
  31598. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31599. geometry.applyToMesh(mesh);
  31600. return geometry;
  31601. };
  31602. Object.defineProperty(Geometry.prototype, "extend", {
  31603. get: function () {
  31604. return this._extend;
  31605. },
  31606. enumerable: true,
  31607. configurable: true
  31608. });
  31609. Geometry.prototype.getScene = function () {
  31610. return this._scene;
  31611. };
  31612. Geometry.prototype.getEngine = function () {
  31613. return this._engine;
  31614. };
  31615. Geometry.prototype.isReady = function () {
  31616. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31617. };
  31618. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31619. get: function () {
  31620. for (var index = 0; index < this._meshes.length; index++) {
  31621. if (!this._meshes[index].doNotSerialize) {
  31622. return false;
  31623. }
  31624. }
  31625. return true;
  31626. },
  31627. enumerable: true,
  31628. configurable: true
  31629. });
  31630. Geometry.prototype._rebuild = function () {
  31631. if (this._vertexArrayObjects) {
  31632. this._vertexArrayObjects = {};
  31633. }
  31634. // Index buffer
  31635. if (this._meshes.length !== 0 && this._indices) {
  31636. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31637. }
  31638. // Vertex buffers
  31639. for (var key in this._vertexBuffers) {
  31640. var vertexBuffer = this._vertexBuffers[key];
  31641. vertexBuffer._rebuild();
  31642. }
  31643. };
  31644. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31645. vertexData.applyToGeometry(this, updatable);
  31646. this.notifyUpdate();
  31647. };
  31648. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31649. if (updatable === void 0) { updatable = false; }
  31650. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31651. this.setVerticesBuffer(buffer);
  31652. };
  31653. Geometry.prototype.removeVerticesData = function (kind) {
  31654. if (this._vertexBuffers[kind]) {
  31655. this._vertexBuffers[kind].dispose();
  31656. delete this._vertexBuffers[kind];
  31657. }
  31658. };
  31659. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31660. var kind = buffer.getKind();
  31661. if (this._vertexBuffers[kind]) {
  31662. this._vertexBuffers[kind].dispose();
  31663. }
  31664. this._vertexBuffers[kind] = buffer;
  31665. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31666. var data = buffer.getData();
  31667. var stride = buffer.getStrideSize();
  31668. this._totalVertices = data.length / stride;
  31669. this.updateExtend(data, stride);
  31670. this._resetPointsArrayCache();
  31671. var meshes = this._meshes;
  31672. var numOfMeshes = meshes.length;
  31673. for (var index = 0; index < numOfMeshes; index++) {
  31674. var mesh = meshes[index];
  31675. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31676. mesh._createGlobalSubMesh(false);
  31677. mesh.computeWorldMatrix(true);
  31678. }
  31679. }
  31680. this.notifyUpdate(kind);
  31681. if (this._vertexArrayObjects) {
  31682. this._disposeVertexArrayObjects();
  31683. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31684. }
  31685. };
  31686. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31687. var vertexBuffer = this.getVertexBuffer(kind);
  31688. if (!vertexBuffer) {
  31689. return;
  31690. }
  31691. vertexBuffer.updateDirectly(data, offset);
  31692. this.notifyUpdate(kind);
  31693. };
  31694. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31695. if (updateExtends === void 0) { updateExtends = false; }
  31696. var vertexBuffer = this.getVertexBuffer(kind);
  31697. if (!vertexBuffer) {
  31698. return;
  31699. }
  31700. vertexBuffer.update(data);
  31701. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31702. var stride = vertexBuffer.getStrideSize();
  31703. this._totalVertices = data.length / stride;
  31704. this.updateBoundingInfo(updateExtends, data);
  31705. }
  31706. this.notifyUpdate(kind);
  31707. };
  31708. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31709. if (updateExtends) {
  31710. this.updateExtend(data);
  31711. }
  31712. var meshes = this._meshes;
  31713. var numOfMeshes = meshes.length;
  31714. this._resetPointsArrayCache();
  31715. for (var index = 0; index < numOfMeshes; index++) {
  31716. var mesh = meshes[index];
  31717. if (updateExtends) {
  31718. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31719. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31720. var subMesh = mesh.subMeshes[subIndex];
  31721. subMesh.refreshBoundingInfo();
  31722. }
  31723. }
  31724. }
  31725. };
  31726. Geometry.prototype._bind = function (effect, indexToBind) {
  31727. if (!effect) {
  31728. return;
  31729. }
  31730. if (indexToBind === undefined) {
  31731. indexToBind = this._indexBuffer;
  31732. }
  31733. var vbs = this.getVertexBuffers();
  31734. if (!vbs) {
  31735. return;
  31736. }
  31737. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31738. this._engine.bindBuffers(vbs, indexToBind, effect);
  31739. return;
  31740. }
  31741. // Using VAO
  31742. if (!this._vertexArrayObjects[effect.key]) {
  31743. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31744. }
  31745. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31746. };
  31747. Geometry.prototype.getTotalVertices = function () {
  31748. if (!this.isReady()) {
  31749. return 0;
  31750. }
  31751. return this._totalVertices;
  31752. };
  31753. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31754. var vertexBuffer = this.getVertexBuffer(kind);
  31755. if (!vertexBuffer) {
  31756. return null;
  31757. }
  31758. var orig = vertexBuffer.getData();
  31759. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31760. return orig;
  31761. }
  31762. else {
  31763. var len = orig.length;
  31764. var copy = [];
  31765. for (var i = 0; i < len; i++) {
  31766. copy.push(orig[i]);
  31767. }
  31768. return copy;
  31769. }
  31770. };
  31771. /**
  31772. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31773. * Possible `kind` values :
  31774. * - BABYLON.VertexBuffer.PositionKind
  31775. * - BABYLON.VertexBuffer.UVKind
  31776. * - BABYLON.VertexBuffer.UV2Kind
  31777. * - BABYLON.VertexBuffer.UV3Kind
  31778. * - BABYLON.VertexBuffer.UV4Kind
  31779. * - BABYLON.VertexBuffer.UV5Kind
  31780. * - BABYLON.VertexBuffer.UV6Kind
  31781. * - BABYLON.VertexBuffer.ColorKind
  31782. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31783. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31784. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31785. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31786. */
  31787. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31788. var vb = this._vertexBuffers[kind];
  31789. if (!vb) {
  31790. return false;
  31791. }
  31792. return vb.isUpdatable();
  31793. };
  31794. Geometry.prototype.getVertexBuffer = function (kind) {
  31795. if (!this.isReady()) {
  31796. return null;
  31797. }
  31798. return this._vertexBuffers[kind];
  31799. };
  31800. Geometry.prototype.getVertexBuffers = function () {
  31801. if (!this.isReady()) {
  31802. return null;
  31803. }
  31804. return this._vertexBuffers;
  31805. };
  31806. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31807. if (!this._vertexBuffers) {
  31808. if (this._delayInfo) {
  31809. return this._delayInfo.indexOf(kind) !== -1;
  31810. }
  31811. return false;
  31812. }
  31813. return this._vertexBuffers[kind] !== undefined;
  31814. };
  31815. Geometry.prototype.getVerticesDataKinds = function () {
  31816. var result = [];
  31817. var kind;
  31818. if (!this._vertexBuffers && this._delayInfo) {
  31819. for (kind in this._delayInfo) {
  31820. result.push(kind);
  31821. }
  31822. }
  31823. else {
  31824. for (kind in this._vertexBuffers) {
  31825. result.push(kind);
  31826. }
  31827. }
  31828. return result;
  31829. };
  31830. Geometry.prototype.updateIndices = function (indices, offset) {
  31831. if (!this._indexBuffer) {
  31832. return;
  31833. }
  31834. if (!this._indexBufferIsUpdatable) {
  31835. this.setIndices(indices, null, true);
  31836. }
  31837. else {
  31838. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31839. }
  31840. };
  31841. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31842. if (totalVertices === void 0) { totalVertices = null; }
  31843. if (updatable === void 0) { updatable = false; }
  31844. if (this._indexBuffer) {
  31845. this._engine._releaseBuffer(this._indexBuffer);
  31846. }
  31847. this._disposeVertexArrayObjects();
  31848. this._indices = indices;
  31849. this._indexBufferIsUpdatable = updatable;
  31850. if (this._meshes.length !== 0 && this._indices) {
  31851. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31852. }
  31853. if (totalVertices != undefined) {
  31854. this._totalVertices = totalVertices;
  31855. }
  31856. var meshes = this._meshes;
  31857. var numOfMeshes = meshes.length;
  31858. for (var index = 0; index < numOfMeshes; index++) {
  31859. meshes[index]._createGlobalSubMesh(true);
  31860. }
  31861. this.notifyUpdate();
  31862. };
  31863. Geometry.prototype.getTotalIndices = function () {
  31864. if (!this.isReady()) {
  31865. return 0;
  31866. }
  31867. return this._indices.length;
  31868. };
  31869. Geometry.prototype.getIndices = function (copyWhenShared) {
  31870. if (!this.isReady()) {
  31871. return null;
  31872. }
  31873. var orig = this._indices;
  31874. if (!copyWhenShared || this._meshes.length === 1) {
  31875. return orig;
  31876. }
  31877. else {
  31878. var len = orig.length;
  31879. var copy = [];
  31880. for (var i = 0; i < len; i++) {
  31881. copy.push(orig[i]);
  31882. }
  31883. return copy;
  31884. }
  31885. };
  31886. Geometry.prototype.getIndexBuffer = function () {
  31887. if (!this.isReady()) {
  31888. return null;
  31889. }
  31890. return this._indexBuffer;
  31891. };
  31892. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31893. if (effect === void 0) { effect = null; }
  31894. if (!effect || !this._vertexArrayObjects) {
  31895. return;
  31896. }
  31897. if (this._vertexArrayObjects[effect.key]) {
  31898. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31899. delete this._vertexArrayObjects[effect.key];
  31900. }
  31901. };
  31902. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31903. var meshes = this._meshes;
  31904. var index = meshes.indexOf(mesh);
  31905. if (index === -1) {
  31906. return;
  31907. }
  31908. meshes.splice(index, 1);
  31909. mesh._geometry = null;
  31910. if (meshes.length === 0 && shouldDispose) {
  31911. this.dispose();
  31912. }
  31913. };
  31914. Geometry.prototype.applyToMesh = function (mesh) {
  31915. if (mesh._geometry === this) {
  31916. return;
  31917. }
  31918. var previousGeometry = mesh._geometry;
  31919. if (previousGeometry) {
  31920. previousGeometry.releaseForMesh(mesh);
  31921. }
  31922. var meshes = this._meshes;
  31923. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31924. mesh._geometry = this;
  31925. this._scene.pushGeometry(this);
  31926. meshes.push(mesh);
  31927. if (this.isReady()) {
  31928. this._applyToMesh(mesh);
  31929. }
  31930. else {
  31931. mesh._boundingInfo = this._boundingInfo;
  31932. }
  31933. };
  31934. Geometry.prototype.updateExtend = function (data, stride) {
  31935. if (data === void 0) { data = null; }
  31936. if (!data) {
  31937. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31938. }
  31939. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31940. };
  31941. Geometry.prototype._applyToMesh = function (mesh) {
  31942. var numOfMeshes = this._meshes.length;
  31943. // vertexBuffers
  31944. for (var kind in this._vertexBuffers) {
  31945. if (numOfMeshes === 1) {
  31946. this._vertexBuffers[kind].create();
  31947. }
  31948. var buffer = this._vertexBuffers[kind].getBuffer();
  31949. if (buffer)
  31950. buffer.references = numOfMeshes;
  31951. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31952. if (!this._extend) {
  31953. this.updateExtend(this._vertexBuffers[kind].getData());
  31954. }
  31955. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31956. mesh._createGlobalSubMesh(false);
  31957. //bounding info was just created again, world matrix should be applied again.
  31958. mesh._updateBoundingInfo();
  31959. }
  31960. }
  31961. // indexBuffer
  31962. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31963. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31964. }
  31965. if (this._indexBuffer) {
  31966. this._indexBuffer.references = numOfMeshes;
  31967. }
  31968. };
  31969. Geometry.prototype.notifyUpdate = function (kind) {
  31970. if (this.onGeometryUpdated) {
  31971. this.onGeometryUpdated(this, kind);
  31972. }
  31973. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31974. var mesh = _a[_i];
  31975. mesh._markSubMeshesAsAttributesDirty();
  31976. }
  31977. };
  31978. Geometry.prototype.load = function (scene, onLoaded) {
  31979. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31980. return;
  31981. }
  31982. if (this.isReady()) {
  31983. if (onLoaded) {
  31984. onLoaded();
  31985. }
  31986. return;
  31987. }
  31988. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31989. this._queueLoad(scene, onLoaded);
  31990. };
  31991. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31992. var _this = this;
  31993. if (!this.delayLoadingFile) {
  31994. return;
  31995. }
  31996. scene._addPendingData(this);
  31997. scene._loadFile(this.delayLoadingFile, function (data) {
  31998. if (!_this._delayLoadingFunction) {
  31999. return;
  32000. }
  32001. _this._delayLoadingFunction(JSON.parse(data), _this);
  32002. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32003. _this._delayInfo = [];
  32004. scene._removePendingData(_this);
  32005. var meshes = _this._meshes;
  32006. var numOfMeshes = meshes.length;
  32007. for (var index = 0; index < numOfMeshes; index++) {
  32008. _this._applyToMesh(meshes[index]);
  32009. }
  32010. if (onLoaded) {
  32011. onLoaded();
  32012. }
  32013. }, undefined, true);
  32014. };
  32015. /**
  32016. * Invert the geometry to move from a right handed system to a left handed one.
  32017. */
  32018. Geometry.prototype.toLeftHanded = function () {
  32019. // Flip faces
  32020. var tIndices = this.getIndices(false);
  32021. if (tIndices != null && tIndices.length > 0) {
  32022. for (var i = 0; i < tIndices.length; i += 3) {
  32023. var tTemp = tIndices[i + 0];
  32024. tIndices[i + 0] = tIndices[i + 2];
  32025. tIndices[i + 2] = tTemp;
  32026. }
  32027. this.setIndices(tIndices);
  32028. }
  32029. // Negate position.z
  32030. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32031. if (tPositions != null && tPositions.length > 0) {
  32032. for (var i = 0; i < tPositions.length; i += 3) {
  32033. tPositions[i + 2] = -tPositions[i + 2];
  32034. }
  32035. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32036. }
  32037. // Negate normal.z
  32038. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32039. if (tNormals != null && tNormals.length > 0) {
  32040. for (var i = 0; i < tNormals.length; i += 3) {
  32041. tNormals[i + 2] = -tNormals[i + 2];
  32042. }
  32043. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32044. }
  32045. };
  32046. // Cache
  32047. Geometry.prototype._resetPointsArrayCache = function () {
  32048. this._positions = null;
  32049. };
  32050. Geometry.prototype._generatePointsArray = function () {
  32051. if (this._positions)
  32052. return true;
  32053. this._positions = [];
  32054. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32055. if (!data) {
  32056. return false;
  32057. }
  32058. for (var index = 0; index < data.length; index += 3) {
  32059. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32060. }
  32061. return true;
  32062. };
  32063. Geometry.prototype.isDisposed = function () {
  32064. return this._isDisposed;
  32065. };
  32066. Geometry.prototype._disposeVertexArrayObjects = function () {
  32067. if (this._vertexArrayObjects) {
  32068. for (var kind in this._vertexArrayObjects) {
  32069. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32070. }
  32071. this._vertexArrayObjects = {};
  32072. }
  32073. };
  32074. Geometry.prototype.dispose = function () {
  32075. var meshes = this._meshes;
  32076. var numOfMeshes = meshes.length;
  32077. var index;
  32078. for (index = 0; index < numOfMeshes; index++) {
  32079. this.releaseForMesh(meshes[index]);
  32080. }
  32081. this._meshes = [];
  32082. this._disposeVertexArrayObjects();
  32083. for (var kind in this._vertexBuffers) {
  32084. this._vertexBuffers[kind].dispose();
  32085. }
  32086. this._vertexBuffers = {};
  32087. this._totalVertices = 0;
  32088. if (this._indexBuffer) {
  32089. this._engine._releaseBuffer(this._indexBuffer);
  32090. }
  32091. this._indexBuffer = null;
  32092. this._indices = [];
  32093. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32094. this.delayLoadingFile = null;
  32095. this._delayLoadingFunction = null;
  32096. this._delayInfo = [];
  32097. this._boundingInfo = null;
  32098. this._scene.removeGeometry(this);
  32099. this._isDisposed = true;
  32100. };
  32101. Geometry.prototype.copy = function (id) {
  32102. var vertexData = new BABYLON.VertexData();
  32103. vertexData.indices = [];
  32104. var indices = this.getIndices();
  32105. if (indices) {
  32106. for (var index = 0; index < indices.length; index++) {
  32107. vertexData.indices.push(indices[index]);
  32108. }
  32109. }
  32110. var updatable = false;
  32111. var stopChecking = false;
  32112. var kind;
  32113. for (kind in this._vertexBuffers) {
  32114. // using slice() to make a copy of the array and not just reference it
  32115. var data = this.getVerticesData(kind);
  32116. if (data instanceof Float32Array) {
  32117. vertexData.set(new Float32Array(data), kind);
  32118. }
  32119. else {
  32120. vertexData.set(data.slice(0), kind);
  32121. }
  32122. if (!stopChecking) {
  32123. var vb = this.getVertexBuffer(kind);
  32124. if (vb) {
  32125. updatable = vb.isUpdatable();
  32126. stopChecking = !updatable;
  32127. }
  32128. }
  32129. }
  32130. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32131. geometry.delayLoadState = this.delayLoadState;
  32132. geometry.delayLoadingFile = this.delayLoadingFile;
  32133. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32134. for (kind in this._delayInfo) {
  32135. geometry._delayInfo = geometry._delayInfo || [];
  32136. geometry._delayInfo.push(kind);
  32137. }
  32138. // Bounding info
  32139. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32140. return geometry;
  32141. };
  32142. Geometry.prototype.serialize = function () {
  32143. var serializationObject = {};
  32144. serializationObject.id = this.id;
  32145. serializationObject.updatable = this._updatable;
  32146. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32147. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32148. }
  32149. return serializationObject;
  32150. };
  32151. Geometry.prototype.toNumberArray = function (origin) {
  32152. if (Array.isArray(origin)) {
  32153. return origin;
  32154. }
  32155. else {
  32156. return Array.prototype.slice.call(origin);
  32157. }
  32158. };
  32159. Geometry.prototype.serializeVerticeData = function () {
  32160. var serializationObject = this.serialize();
  32161. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32162. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32163. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32164. serializationObject.positions._updatable = true;
  32165. }
  32166. }
  32167. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32168. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32169. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32170. serializationObject.normals._updatable = true;
  32171. }
  32172. }
  32173. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32174. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32175. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32176. serializationObject.uvs._updatable = true;
  32177. }
  32178. }
  32179. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32180. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32181. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32182. serializationObject.uv2s._updatable = true;
  32183. }
  32184. }
  32185. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32186. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32187. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32188. serializationObject.uv3s._updatable = true;
  32189. }
  32190. }
  32191. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32192. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32193. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32194. serializationObject.uv4s._updatable = true;
  32195. }
  32196. }
  32197. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32198. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32199. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32200. serializationObject.uv5s._updatable = true;
  32201. }
  32202. }
  32203. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32204. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32205. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32206. serializationObject.uv6s._updatable = true;
  32207. }
  32208. }
  32209. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32210. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32211. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32212. serializationObject.colors._updatable = true;
  32213. }
  32214. }
  32215. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32216. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32217. serializationObject.matricesIndices._isExpanded = true;
  32218. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32219. serializationObject.matricesIndices._updatable = true;
  32220. }
  32221. }
  32222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32223. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32224. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32225. serializationObject.matricesWeights._updatable = true;
  32226. }
  32227. }
  32228. serializationObject.indices = this.toNumberArray(this.getIndices());
  32229. return serializationObject;
  32230. };
  32231. // Statics
  32232. Geometry.ExtractFromMesh = function (mesh, id) {
  32233. var geometry = mesh._geometry;
  32234. if (!geometry) {
  32235. return null;
  32236. }
  32237. return geometry.copy(id);
  32238. };
  32239. /**
  32240. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32241. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32242. * Be aware Math.random() could cause collisions, but:
  32243. * "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"
  32244. */
  32245. Geometry.RandomId = function () {
  32246. return BABYLON.Tools.RandomId();
  32247. };
  32248. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32249. var scene = mesh.getScene();
  32250. // Geometry
  32251. var geometryId = parsedGeometry.geometryId;
  32252. if (geometryId) {
  32253. var geometry = scene.getGeometryByID(geometryId);
  32254. if (geometry) {
  32255. geometry.applyToMesh(mesh);
  32256. }
  32257. }
  32258. else if (parsedGeometry instanceof ArrayBuffer) {
  32259. var binaryInfo = mesh._binaryInfo;
  32260. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32261. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32262. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32263. }
  32264. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32265. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32266. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32267. }
  32268. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32269. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32270. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32271. }
  32272. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32273. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32274. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32275. }
  32276. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32277. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32278. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32279. }
  32280. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32281. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32282. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32283. }
  32284. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32285. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32286. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32287. }
  32288. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32289. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32290. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32291. }
  32292. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32293. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32294. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32295. }
  32296. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32297. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32298. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32299. }
  32300. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32301. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32302. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32303. }
  32304. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32305. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32306. mesh.setIndices(indicesData, null);
  32307. }
  32308. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32309. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32310. mesh.subMeshes = [];
  32311. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32312. var materialIndex = subMeshesData[(i * 5) + 0];
  32313. var verticesStart = subMeshesData[(i * 5) + 1];
  32314. var verticesCount = subMeshesData[(i * 5) + 2];
  32315. var indexStart = subMeshesData[(i * 5) + 3];
  32316. var indexCount = subMeshesData[(i * 5) + 4];
  32317. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32318. }
  32319. }
  32320. }
  32321. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32322. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32323. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32324. if (parsedGeometry.uvs) {
  32325. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32326. }
  32327. if (parsedGeometry.uvs2) {
  32328. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32329. }
  32330. if (parsedGeometry.uvs3) {
  32331. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32332. }
  32333. if (parsedGeometry.uvs4) {
  32334. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32335. }
  32336. if (parsedGeometry.uvs5) {
  32337. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32338. }
  32339. if (parsedGeometry.uvs6) {
  32340. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32341. }
  32342. if (parsedGeometry.colors) {
  32343. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32344. }
  32345. if (parsedGeometry.matricesIndices) {
  32346. if (!parsedGeometry.matricesIndices._isExpanded) {
  32347. var floatIndices = [];
  32348. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32349. var matricesIndex = parsedGeometry.matricesIndices[i];
  32350. floatIndices.push(matricesIndex & 0x000000FF);
  32351. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32352. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32353. floatIndices.push(matricesIndex >> 24);
  32354. }
  32355. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32356. }
  32357. else {
  32358. delete parsedGeometry.matricesIndices._isExpanded;
  32359. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32360. }
  32361. }
  32362. if (parsedGeometry.matricesIndicesExtra) {
  32363. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32364. var floatIndices = [];
  32365. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32366. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32367. floatIndices.push(matricesIndex & 0x000000FF);
  32368. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32369. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32370. floatIndices.push(matricesIndex >> 24);
  32371. }
  32372. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32373. }
  32374. else {
  32375. delete parsedGeometry.matricesIndices._isExpanded;
  32376. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32377. }
  32378. }
  32379. if (parsedGeometry.matricesWeights) {
  32380. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32381. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32382. }
  32383. if (parsedGeometry.matricesWeightsExtra) {
  32384. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32385. }
  32386. mesh.setIndices(parsedGeometry.indices, null);
  32387. }
  32388. // SubMeshes
  32389. if (parsedGeometry.subMeshes) {
  32390. mesh.subMeshes = [];
  32391. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32392. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32393. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32394. }
  32395. }
  32396. // Flat shading
  32397. if (mesh._shouldGenerateFlatShading) {
  32398. mesh.convertToFlatShadedMesh();
  32399. delete mesh._shouldGenerateFlatShading;
  32400. }
  32401. // Update
  32402. mesh.computeWorldMatrix(true);
  32403. // Octree
  32404. var sceneOctree = scene.selectionOctree;
  32405. if (sceneOctree !== undefined && sceneOctree !== null) {
  32406. sceneOctree.addMesh(mesh);
  32407. }
  32408. };
  32409. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32410. var epsilon = 1e-3;
  32411. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32412. return;
  32413. }
  32414. var noInfluenceBoneIndex = 0.0;
  32415. if (parsedGeometry.skeletonId > -1) {
  32416. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32417. if (!skeleton) {
  32418. return;
  32419. }
  32420. noInfluenceBoneIndex = skeleton.bones.length;
  32421. }
  32422. else {
  32423. return;
  32424. }
  32425. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32426. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32427. var matricesWeights = parsedGeometry.matricesWeights;
  32428. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32429. var influencers = parsedGeometry.numBoneInfluencer;
  32430. var size = matricesWeights.length;
  32431. for (var i = 0; i < size; i += 4) {
  32432. var weight = 0.0;
  32433. var firstZeroWeight = -1;
  32434. for (var j = 0; j < 4; j++) {
  32435. var w = matricesWeights[i + j];
  32436. weight += w;
  32437. if (w < epsilon && firstZeroWeight < 0) {
  32438. firstZeroWeight = j;
  32439. }
  32440. }
  32441. if (matricesWeightsExtra) {
  32442. for (var j = 0; j < 4; j++) {
  32443. var w = matricesWeightsExtra[i + j];
  32444. weight += w;
  32445. if (w < epsilon && firstZeroWeight < 0) {
  32446. firstZeroWeight = j + 4;
  32447. }
  32448. }
  32449. }
  32450. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32451. firstZeroWeight = influencers - 1;
  32452. }
  32453. if (weight > epsilon) {
  32454. var mweight = 1.0 / weight;
  32455. for (var j = 0; j < 4; j++) {
  32456. matricesWeights[i + j] *= mweight;
  32457. }
  32458. if (matricesWeightsExtra) {
  32459. for (var j = 0; j < 4; j++) {
  32460. matricesWeightsExtra[i + j] *= mweight;
  32461. }
  32462. }
  32463. }
  32464. else {
  32465. if (firstZeroWeight >= 4) {
  32466. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32467. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32468. }
  32469. else {
  32470. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32471. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32472. }
  32473. }
  32474. }
  32475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32476. if (parsedGeometry.matricesWeightsExtra) {
  32477. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32478. }
  32479. };
  32480. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32481. if (scene.getGeometryByID(parsedVertexData.id)) {
  32482. return null; // null since geometry could be something else than a box...
  32483. }
  32484. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32485. if (BABYLON.Tags) {
  32486. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32487. }
  32488. if (parsedVertexData.delayLoadingFile) {
  32489. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32490. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32491. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32492. geometry._delayInfo = [];
  32493. if (parsedVertexData.hasUVs) {
  32494. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32495. }
  32496. if (parsedVertexData.hasUVs2) {
  32497. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32498. }
  32499. if (parsedVertexData.hasUVs3) {
  32500. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32501. }
  32502. if (parsedVertexData.hasUVs4) {
  32503. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32504. }
  32505. if (parsedVertexData.hasUVs5) {
  32506. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32507. }
  32508. if (parsedVertexData.hasUVs6) {
  32509. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32510. }
  32511. if (parsedVertexData.hasColors) {
  32512. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32513. }
  32514. if (parsedVertexData.hasMatricesIndices) {
  32515. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32516. }
  32517. if (parsedVertexData.hasMatricesWeights) {
  32518. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32519. }
  32520. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32521. }
  32522. else {
  32523. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32524. }
  32525. scene.pushGeometry(geometry, true);
  32526. return geometry;
  32527. };
  32528. return Geometry;
  32529. }());
  32530. BABYLON.Geometry = Geometry;
  32531. /////// Primitives //////////////////////////////////////////////
  32532. //export module Geometry.Primitives {
  32533. /// Abstract class
  32534. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32535. __extends(_PrimitiveGeometry, _super);
  32536. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32537. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32538. if (mesh === void 0) { mesh = null; }
  32539. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32540. _this._canBeRegenerated = _canBeRegenerated;
  32541. _this._beingRegenerated = true;
  32542. _this.regenerate();
  32543. _this._beingRegenerated = false;
  32544. return _this;
  32545. }
  32546. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32547. return this._canBeRegenerated;
  32548. };
  32549. _PrimitiveGeometry.prototype.regenerate = function () {
  32550. if (!this._canBeRegenerated) {
  32551. return;
  32552. }
  32553. this._beingRegenerated = true;
  32554. this.setAllVerticesData(this._regenerateVertexData(), false);
  32555. this._beingRegenerated = false;
  32556. };
  32557. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32558. return _super.prototype.copy.call(this, id);
  32559. };
  32560. // overrides
  32561. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32562. if (!this._beingRegenerated) {
  32563. return;
  32564. }
  32565. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32566. };
  32567. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32568. if (!this._beingRegenerated) {
  32569. return;
  32570. }
  32571. _super.prototype.setVerticesData.call(this, kind, data, false);
  32572. };
  32573. // to override
  32574. // protected
  32575. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32576. throw new Error("Abstract method");
  32577. };
  32578. _PrimitiveGeometry.prototype.copy = function (id) {
  32579. throw new Error("Must be overriden in sub-classes.");
  32580. };
  32581. _PrimitiveGeometry.prototype.serialize = function () {
  32582. var serializationObject = _super.prototype.serialize.call(this);
  32583. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32584. return serializationObject;
  32585. };
  32586. return _PrimitiveGeometry;
  32587. }(Geometry));
  32588. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32589. var RibbonGeometry = /** @class */ (function (_super) {
  32590. __extends(RibbonGeometry, _super);
  32591. // Members
  32592. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32593. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32594. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32595. _this.pathArray = pathArray;
  32596. _this.closeArray = closeArray;
  32597. _this.closePath = closePath;
  32598. _this.offset = offset;
  32599. _this.side = side;
  32600. return _this;
  32601. }
  32602. RibbonGeometry.prototype._regenerateVertexData = function () {
  32603. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32604. };
  32605. RibbonGeometry.prototype.copy = function (id) {
  32606. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32607. };
  32608. return RibbonGeometry;
  32609. }(_PrimitiveGeometry));
  32610. BABYLON.RibbonGeometry = RibbonGeometry;
  32611. var BoxGeometry = /** @class */ (function (_super) {
  32612. __extends(BoxGeometry, _super);
  32613. // Members
  32614. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32615. if (mesh === void 0) { mesh = null; }
  32616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32617. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32618. _this.size = size;
  32619. _this.side = side;
  32620. return _this;
  32621. }
  32622. BoxGeometry.prototype._regenerateVertexData = function () {
  32623. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32624. };
  32625. BoxGeometry.prototype.copy = function (id) {
  32626. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32627. };
  32628. BoxGeometry.prototype.serialize = function () {
  32629. var serializationObject = _super.prototype.serialize.call(this);
  32630. serializationObject.size = this.size;
  32631. return serializationObject;
  32632. };
  32633. BoxGeometry.Parse = function (parsedBox, scene) {
  32634. if (scene.getGeometryByID(parsedBox.id)) {
  32635. return null; // null since geometry could be something else than a box...
  32636. }
  32637. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32638. if (BABYLON.Tags) {
  32639. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32640. }
  32641. scene.pushGeometry(box, true);
  32642. return box;
  32643. };
  32644. return BoxGeometry;
  32645. }(_PrimitiveGeometry));
  32646. BABYLON.BoxGeometry = BoxGeometry;
  32647. var SphereGeometry = /** @class */ (function (_super) {
  32648. __extends(SphereGeometry, _super);
  32649. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32650. if (mesh === void 0) { mesh = null; }
  32651. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32652. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32653. _this.segments = segments;
  32654. _this.diameter = diameter;
  32655. _this.side = side;
  32656. return _this;
  32657. }
  32658. SphereGeometry.prototype._regenerateVertexData = function () {
  32659. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32660. };
  32661. SphereGeometry.prototype.copy = function (id) {
  32662. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32663. };
  32664. SphereGeometry.prototype.serialize = function () {
  32665. var serializationObject = _super.prototype.serialize.call(this);
  32666. serializationObject.segments = this.segments;
  32667. serializationObject.diameter = this.diameter;
  32668. return serializationObject;
  32669. };
  32670. SphereGeometry.Parse = function (parsedSphere, scene) {
  32671. if (scene.getGeometryByID(parsedSphere.id)) {
  32672. return null; // null since geometry could be something else than a sphere...
  32673. }
  32674. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32675. if (BABYLON.Tags) {
  32676. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32677. }
  32678. scene.pushGeometry(sphere, true);
  32679. return sphere;
  32680. };
  32681. return SphereGeometry;
  32682. }(_PrimitiveGeometry));
  32683. BABYLON.SphereGeometry = SphereGeometry;
  32684. var DiscGeometry = /** @class */ (function (_super) {
  32685. __extends(DiscGeometry, _super);
  32686. // Members
  32687. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32688. if (mesh === void 0) { mesh = null; }
  32689. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32690. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32691. _this.radius = radius;
  32692. _this.tessellation = tessellation;
  32693. _this.side = side;
  32694. return _this;
  32695. }
  32696. DiscGeometry.prototype._regenerateVertexData = function () {
  32697. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32698. };
  32699. DiscGeometry.prototype.copy = function (id) {
  32700. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32701. };
  32702. return DiscGeometry;
  32703. }(_PrimitiveGeometry));
  32704. BABYLON.DiscGeometry = DiscGeometry;
  32705. var CylinderGeometry = /** @class */ (function (_super) {
  32706. __extends(CylinderGeometry, _super);
  32707. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32708. if (subdivisions === void 0) { subdivisions = 1; }
  32709. if (mesh === void 0) { mesh = null; }
  32710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32711. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32712. _this.height = height;
  32713. _this.diameterTop = diameterTop;
  32714. _this.diameterBottom = diameterBottom;
  32715. _this.tessellation = tessellation;
  32716. _this.subdivisions = subdivisions;
  32717. _this.side = side;
  32718. return _this;
  32719. }
  32720. CylinderGeometry.prototype._regenerateVertexData = function () {
  32721. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32722. };
  32723. CylinderGeometry.prototype.copy = function (id) {
  32724. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32725. };
  32726. CylinderGeometry.prototype.serialize = function () {
  32727. var serializationObject = _super.prototype.serialize.call(this);
  32728. serializationObject.height = this.height;
  32729. serializationObject.diameterTop = this.diameterTop;
  32730. serializationObject.diameterBottom = this.diameterBottom;
  32731. serializationObject.tessellation = this.tessellation;
  32732. return serializationObject;
  32733. };
  32734. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32735. if (scene.getGeometryByID(parsedCylinder.id)) {
  32736. return null; // null since geometry could be something else than a cylinder...
  32737. }
  32738. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32739. if (BABYLON.Tags) {
  32740. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32741. }
  32742. scene.pushGeometry(cylinder, true);
  32743. return cylinder;
  32744. };
  32745. return CylinderGeometry;
  32746. }(_PrimitiveGeometry));
  32747. BABYLON.CylinderGeometry = CylinderGeometry;
  32748. var TorusGeometry = /** @class */ (function (_super) {
  32749. __extends(TorusGeometry, _super);
  32750. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32751. if (mesh === void 0) { mesh = null; }
  32752. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32753. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32754. _this.diameter = diameter;
  32755. _this.thickness = thickness;
  32756. _this.tessellation = tessellation;
  32757. _this.side = side;
  32758. return _this;
  32759. }
  32760. TorusGeometry.prototype._regenerateVertexData = function () {
  32761. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32762. };
  32763. TorusGeometry.prototype.copy = function (id) {
  32764. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32765. };
  32766. TorusGeometry.prototype.serialize = function () {
  32767. var serializationObject = _super.prototype.serialize.call(this);
  32768. serializationObject.diameter = this.diameter;
  32769. serializationObject.thickness = this.thickness;
  32770. serializationObject.tessellation = this.tessellation;
  32771. return serializationObject;
  32772. };
  32773. TorusGeometry.Parse = function (parsedTorus, scene) {
  32774. if (scene.getGeometryByID(parsedTorus.id)) {
  32775. return null; // null since geometry could be something else than a torus...
  32776. }
  32777. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32778. if (BABYLON.Tags) {
  32779. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32780. }
  32781. scene.pushGeometry(torus, true);
  32782. return torus;
  32783. };
  32784. return TorusGeometry;
  32785. }(_PrimitiveGeometry));
  32786. BABYLON.TorusGeometry = TorusGeometry;
  32787. var GroundGeometry = /** @class */ (function (_super) {
  32788. __extends(GroundGeometry, _super);
  32789. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32790. if (mesh === void 0) { mesh = null; }
  32791. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32792. _this.width = width;
  32793. _this.height = height;
  32794. _this.subdivisions = subdivisions;
  32795. return _this;
  32796. }
  32797. GroundGeometry.prototype._regenerateVertexData = function () {
  32798. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32799. };
  32800. GroundGeometry.prototype.copy = function (id) {
  32801. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32802. };
  32803. GroundGeometry.prototype.serialize = function () {
  32804. var serializationObject = _super.prototype.serialize.call(this);
  32805. serializationObject.width = this.width;
  32806. serializationObject.height = this.height;
  32807. serializationObject.subdivisions = this.subdivisions;
  32808. return serializationObject;
  32809. };
  32810. GroundGeometry.Parse = function (parsedGround, scene) {
  32811. if (scene.getGeometryByID(parsedGround.id)) {
  32812. return null; // null since geometry could be something else than a ground...
  32813. }
  32814. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32815. if (BABYLON.Tags) {
  32816. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32817. }
  32818. scene.pushGeometry(ground, true);
  32819. return ground;
  32820. };
  32821. return GroundGeometry;
  32822. }(_PrimitiveGeometry));
  32823. BABYLON.GroundGeometry = GroundGeometry;
  32824. var TiledGroundGeometry = /** @class */ (function (_super) {
  32825. __extends(TiledGroundGeometry, _super);
  32826. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32827. if (mesh === void 0) { mesh = null; }
  32828. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32829. _this.xmin = xmin;
  32830. _this.zmin = zmin;
  32831. _this.xmax = xmax;
  32832. _this.zmax = zmax;
  32833. _this.subdivisions = subdivisions;
  32834. _this.precision = precision;
  32835. return _this;
  32836. }
  32837. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32838. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32839. };
  32840. TiledGroundGeometry.prototype.copy = function (id) {
  32841. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32842. };
  32843. return TiledGroundGeometry;
  32844. }(_PrimitiveGeometry));
  32845. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32846. var PlaneGeometry = /** @class */ (function (_super) {
  32847. __extends(PlaneGeometry, _super);
  32848. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32849. if (mesh === void 0) { mesh = null; }
  32850. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32851. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32852. _this.size = size;
  32853. _this.side = side;
  32854. return _this;
  32855. }
  32856. PlaneGeometry.prototype._regenerateVertexData = function () {
  32857. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32858. };
  32859. PlaneGeometry.prototype.copy = function (id) {
  32860. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32861. };
  32862. PlaneGeometry.prototype.serialize = function () {
  32863. var serializationObject = _super.prototype.serialize.call(this);
  32864. serializationObject.size = this.size;
  32865. return serializationObject;
  32866. };
  32867. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32868. if (scene.getGeometryByID(parsedPlane.id)) {
  32869. return null; // null since geometry could be something else than a ground...
  32870. }
  32871. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32872. if (BABYLON.Tags) {
  32873. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32874. }
  32875. scene.pushGeometry(plane, true);
  32876. return plane;
  32877. };
  32878. return PlaneGeometry;
  32879. }(_PrimitiveGeometry));
  32880. BABYLON.PlaneGeometry = PlaneGeometry;
  32881. var TorusKnotGeometry = /** @class */ (function (_super) {
  32882. __extends(TorusKnotGeometry, _super);
  32883. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32884. if (mesh === void 0) { mesh = null; }
  32885. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32886. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32887. _this.radius = radius;
  32888. _this.tube = tube;
  32889. _this.radialSegments = radialSegments;
  32890. _this.tubularSegments = tubularSegments;
  32891. _this.p = p;
  32892. _this.q = q;
  32893. _this.side = side;
  32894. return _this;
  32895. }
  32896. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32897. 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 });
  32898. };
  32899. TorusKnotGeometry.prototype.copy = function (id) {
  32900. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32901. };
  32902. TorusKnotGeometry.prototype.serialize = function () {
  32903. var serializationObject = _super.prototype.serialize.call(this);
  32904. serializationObject.radius = this.radius;
  32905. serializationObject.tube = this.tube;
  32906. serializationObject.radialSegments = this.radialSegments;
  32907. serializationObject.tubularSegments = this.tubularSegments;
  32908. serializationObject.p = this.p;
  32909. serializationObject.q = this.q;
  32910. return serializationObject;
  32911. };
  32912. ;
  32913. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32914. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32915. return null; // null since geometry could be something else than a ground...
  32916. }
  32917. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32918. if (BABYLON.Tags) {
  32919. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32920. }
  32921. scene.pushGeometry(torusKnot, true);
  32922. return torusKnot;
  32923. };
  32924. return TorusKnotGeometry;
  32925. }(_PrimitiveGeometry));
  32926. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32927. //}
  32928. })(BABYLON || (BABYLON = {}));
  32929. //# sourceMappingURL=babylon.geometry.js.map
  32930. var BABYLON;
  32931. (function (BABYLON) {
  32932. var PostProcessManager = /** @class */ (function () {
  32933. function PostProcessManager(scene) {
  32934. this._vertexBuffers = {};
  32935. this._scene = scene;
  32936. }
  32937. PostProcessManager.prototype._prepareBuffers = function () {
  32938. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32939. return;
  32940. }
  32941. // VBO
  32942. var vertices = [];
  32943. vertices.push(1, 1);
  32944. vertices.push(-1, 1);
  32945. vertices.push(-1, -1);
  32946. vertices.push(1, -1);
  32947. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32948. this._buildIndexBuffer();
  32949. };
  32950. PostProcessManager.prototype._buildIndexBuffer = function () {
  32951. // Indices
  32952. var indices = [];
  32953. indices.push(0);
  32954. indices.push(1);
  32955. indices.push(2);
  32956. indices.push(0);
  32957. indices.push(2);
  32958. indices.push(3);
  32959. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32960. };
  32961. PostProcessManager.prototype._rebuild = function () {
  32962. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32963. if (!vb) {
  32964. return;
  32965. }
  32966. vb._rebuild();
  32967. this._buildIndexBuffer();
  32968. };
  32969. // Methods
  32970. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32971. if (sourceTexture === void 0) { sourceTexture = null; }
  32972. if (postProcesses === void 0) { postProcesses = null; }
  32973. var camera = this._scene.activeCamera;
  32974. if (!camera) {
  32975. return false;
  32976. }
  32977. var postProcesses = postProcesses || camera._postProcesses;
  32978. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32979. return false;
  32980. }
  32981. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32982. return true;
  32983. };
  32984. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32985. if (targetTexture === void 0) { targetTexture = null; }
  32986. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32987. var engine = this._scene.getEngine();
  32988. for (var index = 0; index < postProcesses.length; index++) {
  32989. if (index < postProcesses.length - 1) {
  32990. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32991. }
  32992. else {
  32993. if (targetTexture) {
  32994. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32995. }
  32996. else {
  32997. engine.restoreDefaultFramebuffer();
  32998. }
  32999. }
  33000. var pp = postProcesses[index];
  33001. var effect = pp.apply();
  33002. if (effect) {
  33003. pp.onBeforeRenderObservable.notifyObservers(effect);
  33004. // VBOs
  33005. this._prepareBuffers();
  33006. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33007. // Draw order
  33008. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33009. pp.onAfterRenderObservable.notifyObservers(effect);
  33010. }
  33011. }
  33012. // Restore depth buffer
  33013. engine.setDepthBuffer(true);
  33014. engine.setDepthWrite(true);
  33015. };
  33016. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33017. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33018. var camera = this._scene.activeCamera;
  33019. if (!camera) {
  33020. return;
  33021. }
  33022. postProcesses = postProcesses || camera._postProcesses;
  33023. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33024. return;
  33025. }
  33026. var engine = this._scene.getEngine();
  33027. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33028. if (index < len - 1) {
  33029. postProcesses[index + 1].activate(camera, targetTexture);
  33030. }
  33031. else {
  33032. if (targetTexture) {
  33033. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33034. }
  33035. else {
  33036. engine.restoreDefaultFramebuffer();
  33037. }
  33038. }
  33039. if (doNotPresent) {
  33040. break;
  33041. }
  33042. var pp = postProcesses[index];
  33043. var effect = pp.apply();
  33044. if (effect) {
  33045. pp.onBeforeRenderObservable.notifyObservers(effect);
  33046. // VBOs
  33047. this._prepareBuffers();
  33048. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33049. // Draw order
  33050. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33051. pp.onAfterRenderObservable.notifyObservers(effect);
  33052. }
  33053. }
  33054. // Restore states
  33055. engine.setDepthBuffer(true);
  33056. engine.setDepthWrite(true);
  33057. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33058. };
  33059. PostProcessManager.prototype.dispose = function () {
  33060. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33061. if (buffer) {
  33062. buffer.dispose();
  33063. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33064. }
  33065. if (this._indexBuffer) {
  33066. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33067. this._indexBuffer = null;
  33068. }
  33069. };
  33070. return PostProcessManager;
  33071. }());
  33072. BABYLON.PostProcessManager = PostProcessManager;
  33073. })(BABYLON || (BABYLON = {}));
  33074. //# sourceMappingURL=babylon.postProcessManager.js.map
  33075. var BABYLON;
  33076. (function (BABYLON) {
  33077. /**
  33078. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33079. */
  33080. var PerformanceMonitor = /** @class */ (function () {
  33081. /**
  33082. * constructor
  33083. * @param frameSampleSize The number of samples required to saturate the sliding window
  33084. */
  33085. function PerformanceMonitor(frameSampleSize) {
  33086. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33087. this._enabled = true;
  33088. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33089. }
  33090. /**
  33091. * Samples current frame
  33092. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33093. */
  33094. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33095. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33096. if (!this._enabled)
  33097. return;
  33098. if (this._lastFrameTimeMs != null) {
  33099. var dt = timeMs - this._lastFrameTimeMs;
  33100. this._rollingFrameTime.add(dt);
  33101. }
  33102. this._lastFrameTimeMs = timeMs;
  33103. };
  33104. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33105. /**
  33106. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33107. * @return Average frame time in milliseconds
  33108. */
  33109. get: function () {
  33110. return this._rollingFrameTime.average;
  33111. },
  33112. enumerable: true,
  33113. configurable: true
  33114. });
  33115. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33116. /**
  33117. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33118. * @return Frame time variance in milliseconds squared
  33119. */
  33120. get: function () {
  33121. return this._rollingFrameTime.variance;
  33122. },
  33123. enumerable: true,
  33124. configurable: true
  33125. });
  33126. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33127. /**
  33128. * Returns the frame time of the most recent frame
  33129. * @return Frame time in milliseconds
  33130. */
  33131. get: function () {
  33132. return this._rollingFrameTime.history(0);
  33133. },
  33134. enumerable: true,
  33135. configurable: true
  33136. });
  33137. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33138. /**
  33139. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33140. * @return Framerate in frames per second
  33141. */
  33142. get: function () {
  33143. return 1000.0 / this._rollingFrameTime.average;
  33144. },
  33145. enumerable: true,
  33146. configurable: true
  33147. });
  33148. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33149. /**
  33150. * Returns the average framerate in frames per second using the most recent frame time
  33151. * @return Framerate in frames per second
  33152. */
  33153. get: function () {
  33154. var history = this._rollingFrameTime.history(0);
  33155. if (history === 0) {
  33156. return 0;
  33157. }
  33158. return 1000.0 / history;
  33159. },
  33160. enumerable: true,
  33161. configurable: true
  33162. });
  33163. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33164. /**
  33165. * Returns true if enough samples have been taken to completely fill the sliding window
  33166. * @return true if saturated
  33167. */
  33168. get: function () {
  33169. return this._rollingFrameTime.isSaturated();
  33170. },
  33171. enumerable: true,
  33172. configurable: true
  33173. });
  33174. /**
  33175. * Enables contributions to the sliding window sample set
  33176. */
  33177. PerformanceMonitor.prototype.enable = function () {
  33178. this._enabled = true;
  33179. };
  33180. /**
  33181. * Disables contributions to the sliding window sample set
  33182. * Samples will not be interpolated over the disabled period
  33183. */
  33184. PerformanceMonitor.prototype.disable = function () {
  33185. this._enabled = false;
  33186. //clear last sample to avoid interpolating over the disabled period when next enabled
  33187. this._lastFrameTimeMs = null;
  33188. };
  33189. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33190. /**
  33191. * Returns true if sampling is enabled
  33192. * @return true if enabled
  33193. */
  33194. get: function () {
  33195. return this._enabled;
  33196. },
  33197. enumerable: true,
  33198. configurable: true
  33199. });
  33200. /**
  33201. * Resets performance monitor
  33202. */
  33203. PerformanceMonitor.prototype.reset = function () {
  33204. //clear last sample to avoid interpolating over the disabled period when next enabled
  33205. this._lastFrameTimeMs = null;
  33206. //wipe record
  33207. this._rollingFrameTime.reset();
  33208. };
  33209. return PerformanceMonitor;
  33210. }());
  33211. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33212. /**
  33213. * RollingAverage
  33214. *
  33215. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33216. */
  33217. var RollingAverage = /** @class */ (function () {
  33218. /**
  33219. * constructor
  33220. * @param length The number of samples required to saturate the sliding window
  33221. */
  33222. function RollingAverage(length) {
  33223. this._samples = new Array(length);
  33224. this.reset();
  33225. }
  33226. /**
  33227. * Adds a sample to the sample set
  33228. * @param v The sample value
  33229. */
  33230. RollingAverage.prototype.add = function (v) {
  33231. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33232. var delta;
  33233. //we need to check if we've already wrapped round
  33234. if (this.isSaturated()) {
  33235. //remove bottom of stack from mean
  33236. var bottomValue = this._samples[this._pos];
  33237. delta = bottomValue - this.average;
  33238. this.average -= delta / (this._sampleCount - 1);
  33239. this._m2 -= delta * (bottomValue - this.average);
  33240. }
  33241. else {
  33242. this._sampleCount++;
  33243. }
  33244. //add new value to mean
  33245. delta = v - this.average;
  33246. this.average += delta / (this._sampleCount);
  33247. this._m2 += delta * (v - this.average);
  33248. //set the new variance
  33249. this.variance = this._m2 / (this._sampleCount - 1);
  33250. this._samples[this._pos] = v;
  33251. this._pos++;
  33252. this._pos %= this._samples.length; //positive wrap around
  33253. };
  33254. /**
  33255. * Returns previously added values or null if outside of history or outside the sliding window domain
  33256. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33257. * @return Value previously recorded with add() or null if outside of range
  33258. */
  33259. RollingAverage.prototype.history = function (i) {
  33260. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33261. return 0;
  33262. }
  33263. var i0 = this._wrapPosition(this._pos - 1.0);
  33264. return this._samples[this._wrapPosition(i0 - i)];
  33265. };
  33266. /**
  33267. * Returns true if enough samples have been taken to completely fill the sliding window
  33268. * @return true if sample-set saturated
  33269. */
  33270. RollingAverage.prototype.isSaturated = function () {
  33271. return this._sampleCount >= this._samples.length;
  33272. };
  33273. /**
  33274. * Resets the rolling average (equivalent to 0 samples taken so far)
  33275. */
  33276. RollingAverage.prototype.reset = function () {
  33277. this.average = 0;
  33278. this.variance = 0;
  33279. this._sampleCount = 0;
  33280. this._pos = 0;
  33281. this._m2 = 0;
  33282. };
  33283. /**
  33284. * Wraps a value around the sample range boundaries
  33285. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33286. * @return Wrapped position in sample range
  33287. */
  33288. RollingAverage.prototype._wrapPosition = function (i) {
  33289. var max = this._samples.length;
  33290. return ((i % max) + max) % max;
  33291. };
  33292. return RollingAverage;
  33293. }());
  33294. BABYLON.RollingAverage = RollingAverage;
  33295. })(BABYLON || (BABYLON = {}));
  33296. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33297. var BABYLON;
  33298. (function (BABYLON) {
  33299. /**
  33300. * This groups together the common properties used for image processing either in direct forward pass
  33301. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33302. * or not.
  33303. */
  33304. var ImageProcessingConfiguration = /** @class */ (function () {
  33305. function ImageProcessingConfiguration() {
  33306. /**
  33307. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33308. */
  33309. this.colorCurves = new BABYLON.ColorCurves();
  33310. this._colorCurvesEnabled = false;
  33311. this._colorGradingEnabled = false;
  33312. this._colorGradingWithGreenDepth = true;
  33313. this._colorGradingBGR = true;
  33314. this._exposure = 1.0;
  33315. this._toneMappingEnabled = false;
  33316. this._contrast = 1.0;
  33317. /**
  33318. * Vignette stretch size.
  33319. */
  33320. this.vignetteStretch = 0;
  33321. /**
  33322. * Vignette centre X Offset.
  33323. */
  33324. this.vignetteCentreX = 0;
  33325. /**
  33326. * Vignette centre Y Offset.
  33327. */
  33328. this.vignetteCentreY = 0;
  33329. /**
  33330. * Vignette weight or intensity of the vignette effect.
  33331. */
  33332. this.vignetteWeight = 1.5;
  33333. /**
  33334. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33335. * if vignetteEnabled is set to true.
  33336. */
  33337. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33338. /**
  33339. * Camera field of view used by the Vignette effect.
  33340. */
  33341. this.vignetteCameraFov = 0.5;
  33342. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33343. this._vignetteEnabled = false;
  33344. this._applyByPostProcess = false;
  33345. this._isEnabled = true;
  33346. /**
  33347. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33348. * @type {BABYLON.Observable}
  33349. */
  33350. this.onUpdateParameters = new BABYLON.Observable();
  33351. }
  33352. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33353. /**
  33354. * Gets wether the color curves effect is enabled.
  33355. */
  33356. get: function () {
  33357. return this._colorCurvesEnabled;
  33358. },
  33359. /**
  33360. * Sets wether the color curves effect is enabled.
  33361. */
  33362. set: function (value) {
  33363. if (this._colorCurvesEnabled === value) {
  33364. return;
  33365. }
  33366. this._colorCurvesEnabled = value;
  33367. this._updateParameters();
  33368. },
  33369. enumerable: true,
  33370. configurable: true
  33371. });
  33372. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33373. /**
  33374. * Gets wether the color grading effect is enabled.
  33375. */
  33376. get: function () {
  33377. return this._colorGradingEnabled;
  33378. },
  33379. /**
  33380. * Sets wether the color grading effect is enabled.
  33381. */
  33382. set: function (value) {
  33383. if (this._colorGradingEnabled === value) {
  33384. return;
  33385. }
  33386. this._colorGradingEnabled = value;
  33387. this._updateParameters();
  33388. },
  33389. enumerable: true,
  33390. configurable: true
  33391. });
  33392. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33393. /**
  33394. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33395. */
  33396. get: function () {
  33397. return this._colorGradingWithGreenDepth;
  33398. },
  33399. /**
  33400. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33401. */
  33402. set: function (value) {
  33403. if (this._colorGradingWithGreenDepth === value) {
  33404. return;
  33405. }
  33406. this._colorGradingWithGreenDepth = value;
  33407. this._updateParameters();
  33408. },
  33409. enumerable: true,
  33410. configurable: true
  33411. });
  33412. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33413. /**
  33414. * Gets wether the color grading texture contains BGR values.
  33415. */
  33416. get: function () {
  33417. return this._colorGradingBGR;
  33418. },
  33419. /**
  33420. * Sets wether the color grading texture contains BGR values.
  33421. */
  33422. set: function (value) {
  33423. if (this._colorGradingBGR === value) {
  33424. return;
  33425. }
  33426. this._colorGradingBGR = value;
  33427. this._updateParameters();
  33428. },
  33429. enumerable: true,
  33430. configurable: true
  33431. });
  33432. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33433. /**
  33434. * Gets the Exposure used in the effect.
  33435. */
  33436. get: function () {
  33437. return this._exposure;
  33438. },
  33439. /**
  33440. * Sets the Exposure used in the effect.
  33441. */
  33442. set: function (value) {
  33443. if (this._exposure === value) {
  33444. return;
  33445. }
  33446. this._exposure = value;
  33447. this._updateParameters();
  33448. },
  33449. enumerable: true,
  33450. configurable: true
  33451. });
  33452. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33453. /**
  33454. * Gets wether the tone mapping effect is enabled.
  33455. */
  33456. get: function () {
  33457. return this._toneMappingEnabled;
  33458. },
  33459. /**
  33460. * Sets wether the tone mapping effect is enabled.
  33461. */
  33462. set: function (value) {
  33463. if (this._toneMappingEnabled === value) {
  33464. return;
  33465. }
  33466. this._toneMappingEnabled = value;
  33467. this._updateParameters();
  33468. },
  33469. enumerable: true,
  33470. configurable: true
  33471. });
  33472. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33473. /**
  33474. * Gets the contrast used in the effect.
  33475. */
  33476. get: function () {
  33477. return this._contrast;
  33478. },
  33479. /**
  33480. * Sets the contrast used in the effect.
  33481. */
  33482. set: function (value) {
  33483. if (this._contrast === value) {
  33484. return;
  33485. }
  33486. this._contrast = value;
  33487. this._updateParameters();
  33488. },
  33489. enumerable: true,
  33490. configurable: true
  33491. });
  33492. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33493. /**
  33494. * Gets the vignette blend mode allowing different kind of effect.
  33495. */
  33496. get: function () {
  33497. return this._vignetteBlendMode;
  33498. },
  33499. /**
  33500. * Sets the vignette blend mode allowing different kind of effect.
  33501. */
  33502. set: function (value) {
  33503. if (this._vignetteBlendMode === value) {
  33504. return;
  33505. }
  33506. this._vignetteBlendMode = value;
  33507. this._updateParameters();
  33508. },
  33509. enumerable: true,
  33510. configurable: true
  33511. });
  33512. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33513. /**
  33514. * Gets wether the vignette effect is enabled.
  33515. */
  33516. get: function () {
  33517. return this._vignetteEnabled;
  33518. },
  33519. /**
  33520. * Sets wether the vignette effect is enabled.
  33521. */
  33522. set: function (value) {
  33523. if (this._vignetteEnabled === value) {
  33524. return;
  33525. }
  33526. this._vignetteEnabled = value;
  33527. this._updateParameters();
  33528. },
  33529. enumerable: true,
  33530. configurable: true
  33531. });
  33532. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33533. /**
  33534. * Gets wether the image processing is applied through a post process or not.
  33535. */
  33536. get: function () {
  33537. return this._applyByPostProcess;
  33538. },
  33539. /**
  33540. * Sets wether the image processing is applied through a post process or not.
  33541. */
  33542. set: function (value) {
  33543. if (this._applyByPostProcess === value) {
  33544. return;
  33545. }
  33546. this._applyByPostProcess = value;
  33547. this._updateParameters();
  33548. },
  33549. enumerable: true,
  33550. configurable: true
  33551. });
  33552. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33553. /**
  33554. * Gets wether the image processing is enabled or not.
  33555. */
  33556. get: function () {
  33557. return this._isEnabled;
  33558. },
  33559. /**
  33560. * Sets wether the image processing is enabled or not.
  33561. */
  33562. set: function (value) {
  33563. if (this._isEnabled === value) {
  33564. return;
  33565. }
  33566. this._isEnabled = value;
  33567. this._updateParameters();
  33568. },
  33569. enumerable: true,
  33570. configurable: true
  33571. });
  33572. /**
  33573. * Method called each time the image processing information changes requires to recompile the effect.
  33574. */
  33575. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33576. this.onUpdateParameters.notifyObservers(this);
  33577. };
  33578. ImageProcessingConfiguration.prototype.getClassName = function () {
  33579. return "ImageProcessingConfiguration";
  33580. };
  33581. /**
  33582. * Prepare the list of uniforms associated with the Image Processing effects.
  33583. * @param uniformsList The list of uniforms used in the effect
  33584. * @param defines the list of defines currently in use
  33585. */
  33586. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33587. if (defines.EXPOSURE) {
  33588. uniforms.push("exposureLinear");
  33589. }
  33590. if (defines.CONTRAST) {
  33591. uniforms.push("contrast");
  33592. }
  33593. if (defines.COLORGRADING) {
  33594. uniforms.push("colorTransformSettings");
  33595. }
  33596. if (defines.VIGNETTE) {
  33597. uniforms.push("vInverseScreenSize");
  33598. uniforms.push("vignetteSettings1");
  33599. uniforms.push("vignetteSettings2");
  33600. }
  33601. if (defines.COLORCURVES) {
  33602. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33603. }
  33604. };
  33605. /**
  33606. * Prepare the list of samplers associated with the Image Processing effects.
  33607. * @param uniformsList The list of uniforms used in the effect
  33608. * @param defines the list of defines currently in use
  33609. */
  33610. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33611. if (defines.COLORGRADING) {
  33612. samplersList.push("txColorTransform");
  33613. }
  33614. };
  33615. /**
  33616. * Prepare the list of defines associated to the shader.
  33617. * @param defines the list of defines to complete
  33618. */
  33619. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33620. if (forPostProcess === void 0) { forPostProcess = false; }
  33621. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33622. defines.VIGNETTE = false;
  33623. defines.TONEMAPPING = false;
  33624. defines.CONTRAST = false;
  33625. defines.EXPOSURE = false;
  33626. defines.COLORCURVES = false;
  33627. defines.COLORGRADING = false;
  33628. defines.COLORGRADING3D = false;
  33629. defines.IMAGEPROCESSING = false;
  33630. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33631. return;
  33632. }
  33633. defines.VIGNETTE = this.vignetteEnabled;
  33634. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33635. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33636. defines.TONEMAPPING = this.toneMappingEnabled;
  33637. defines.CONTRAST = (this.contrast !== 1.0);
  33638. defines.EXPOSURE = (this.exposure !== 1.0);
  33639. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33640. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33641. if (defines.COLORGRADING) {
  33642. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33643. }
  33644. else {
  33645. defines.COLORGRADING3D = false;
  33646. }
  33647. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33648. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33649. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33650. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33651. };
  33652. /**
  33653. * Returns true if all the image processing information are ready.
  33654. */
  33655. ImageProcessingConfiguration.prototype.isReady = function () {
  33656. // Color Grading texure can not be none blocking.
  33657. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33658. };
  33659. /**
  33660. * Binds the image processing to the shader.
  33661. * @param effect The effect to bind to
  33662. */
  33663. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33664. if (aspectRatio === void 0) { aspectRatio = 1; }
  33665. // Color Curves
  33666. if (this._colorCurvesEnabled && this.colorCurves) {
  33667. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33668. }
  33669. // Vignette
  33670. if (this._vignetteEnabled) {
  33671. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33672. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33673. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33674. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33675. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33676. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33677. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33678. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33679. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33680. var vignettePower = -2.0 * this.vignetteWeight;
  33681. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33682. }
  33683. // Exposure
  33684. effect.setFloat("exposureLinear", this.exposure);
  33685. // Contrast
  33686. effect.setFloat("contrast", this.contrast);
  33687. // Color transform settings
  33688. if (this.colorGradingTexture) {
  33689. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33690. var textureSize = this.colorGradingTexture.getSize().height;
  33691. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33692. 0.5 / textureSize, // textureOffset
  33693. textureSize, // textureSize
  33694. this.colorGradingTexture.level // weight
  33695. );
  33696. }
  33697. };
  33698. /**
  33699. * Clones the current image processing instance.
  33700. * @return The cloned image processing
  33701. */
  33702. ImageProcessingConfiguration.prototype.clone = function () {
  33703. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33704. };
  33705. /**
  33706. * Serializes the current image processing instance to a json representation.
  33707. * @return a JSON representation
  33708. */
  33709. ImageProcessingConfiguration.prototype.serialize = function () {
  33710. return BABYLON.SerializationHelper.Serialize(this);
  33711. };
  33712. /**
  33713. * Parses the image processing from a json representation.
  33714. * @param source the JSON source to parse
  33715. * @return The parsed image processing
  33716. */
  33717. ImageProcessingConfiguration.Parse = function (source) {
  33718. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33719. };
  33720. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33721. /**
  33722. * Used to apply the vignette as a mix with the pixel color.
  33723. */
  33724. get: function () {
  33725. return this._VIGNETTEMODE_MULTIPLY;
  33726. },
  33727. enumerable: true,
  33728. configurable: true
  33729. });
  33730. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33731. /**
  33732. * Used to apply the vignette as a replacement of the pixel color.
  33733. */
  33734. get: function () {
  33735. return this._VIGNETTEMODE_OPAQUE;
  33736. },
  33737. enumerable: true,
  33738. configurable: true
  33739. });
  33740. // Static constants associated to the image processing.
  33741. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33742. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33743. __decorate([
  33744. BABYLON.serializeAsColorCurves()
  33745. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33746. __decorate([
  33747. BABYLON.serialize()
  33748. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33749. __decorate([
  33750. BABYLON.serializeAsTexture()
  33751. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33752. __decorate([
  33753. BABYLON.serialize()
  33754. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33755. __decorate([
  33756. BABYLON.serialize()
  33757. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33758. __decorate([
  33759. BABYLON.serialize()
  33760. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33761. __decorate([
  33762. BABYLON.serialize()
  33763. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33764. __decorate([
  33765. BABYLON.serialize()
  33766. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33767. __decorate([
  33768. BABYLON.serialize()
  33769. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33770. __decorate([
  33771. BABYLON.serialize()
  33772. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33773. __decorate([
  33774. BABYLON.serialize()
  33775. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33776. __decorate([
  33777. BABYLON.serialize()
  33778. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33779. __decorate([
  33780. BABYLON.serialize()
  33781. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33782. __decorate([
  33783. BABYLON.serializeAsColor4()
  33784. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33785. __decorate([
  33786. BABYLON.serialize()
  33787. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33788. __decorate([
  33789. BABYLON.serialize()
  33790. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33791. __decorate([
  33792. BABYLON.serialize()
  33793. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33794. __decorate([
  33795. BABYLON.serialize()
  33796. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33797. __decorate([
  33798. BABYLON.serialize()
  33799. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33800. return ImageProcessingConfiguration;
  33801. }());
  33802. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33803. })(BABYLON || (BABYLON = {}));
  33804. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33805. var BABYLON;
  33806. (function (BABYLON) {
  33807. /**
  33808. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33809. * It can help converting any input color in a desired output one. This can then be used to create effects
  33810. * from sepia, black and white to sixties or futuristic rendering...
  33811. *
  33812. * The only supported format is currently 3dl.
  33813. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33814. */
  33815. var ColorGradingTexture = /** @class */ (function (_super) {
  33816. __extends(ColorGradingTexture, _super);
  33817. /**
  33818. * Instantiates a ColorGradingTexture from the following parameters.
  33819. *
  33820. * @param url The location of the color gradind data (currently only supporting 3dl)
  33821. * @param scene The scene the texture will be used in
  33822. */
  33823. function ColorGradingTexture(url, scene) {
  33824. var _this = _super.call(this, scene) || this;
  33825. if (!url) {
  33826. return _this;
  33827. }
  33828. _this._engine = scene.getEngine();
  33829. _this._textureMatrix = BABYLON.Matrix.Identity();
  33830. _this.name = url;
  33831. _this.url = url;
  33832. _this.hasAlpha = false;
  33833. _this.isCube = false;
  33834. _this.is3D = _this._engine.webGLVersion > 1;
  33835. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33836. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33837. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33838. _this.anisotropicFilteringLevel = 1;
  33839. _this._texture = _this._getFromCache(url, true);
  33840. if (!_this._texture) {
  33841. if (!scene.useDelayedTextureLoading) {
  33842. _this.loadTexture();
  33843. }
  33844. else {
  33845. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33846. }
  33847. }
  33848. return _this;
  33849. }
  33850. /**
  33851. * Returns the texture matrix used in most of the material.
  33852. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33853. */
  33854. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33855. return this._textureMatrix;
  33856. };
  33857. /**
  33858. * Occurs when the file being loaded is a .3dl LUT file.
  33859. */
  33860. ColorGradingTexture.prototype.load3dlTexture = function () {
  33861. var engine = this._engine;
  33862. var texture;
  33863. if (engine.webGLVersion === 1) {
  33864. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33865. }
  33866. else {
  33867. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33868. }
  33869. this._texture = texture;
  33870. var callback = function (text) {
  33871. if (typeof text !== "string") {
  33872. return;
  33873. }
  33874. var data = null;
  33875. var tempData = null;
  33876. var line;
  33877. var lines = text.split('\n');
  33878. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33879. var maxColor = 0;
  33880. for (var i = 0; i < lines.length; i++) {
  33881. line = lines[i];
  33882. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33883. continue;
  33884. if (line.indexOf('#') === 0)
  33885. continue;
  33886. var words = line.split(" ");
  33887. if (size === 0) {
  33888. // Number of space + one
  33889. size = words.length;
  33890. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33891. tempData = new Float32Array(size * size * size * 4);
  33892. continue;
  33893. }
  33894. if (size != 0) {
  33895. var r = Math.max(parseInt(words[0]), 0);
  33896. var g = Math.max(parseInt(words[1]), 0);
  33897. var b = Math.max(parseInt(words[2]), 0);
  33898. maxColor = Math.max(r, maxColor);
  33899. maxColor = Math.max(g, maxColor);
  33900. maxColor = Math.max(b, maxColor);
  33901. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33902. if (tempData) {
  33903. tempData[pixelStorageIndex + 0] = r;
  33904. tempData[pixelStorageIndex + 1] = g;
  33905. tempData[pixelStorageIndex + 2] = b;
  33906. }
  33907. pixelIndexSlice++;
  33908. if (pixelIndexSlice % size == 0) {
  33909. pixelIndexH++;
  33910. pixelIndexSlice = 0;
  33911. if (pixelIndexH % size == 0) {
  33912. pixelIndexW++;
  33913. pixelIndexH = 0;
  33914. }
  33915. }
  33916. }
  33917. }
  33918. if (tempData && data) {
  33919. for (var i = 0; i < tempData.length; i++) {
  33920. if (i > 0 && (i + 1) % 4 === 0) {
  33921. data[i] = 255;
  33922. }
  33923. else {
  33924. var value = tempData[i];
  33925. data[i] = (value / maxColor * 255);
  33926. }
  33927. }
  33928. }
  33929. if (texture.is3D) {
  33930. texture.updateSize(size, size, size);
  33931. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33932. }
  33933. else {
  33934. texture.updateSize(size * size, size);
  33935. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33936. }
  33937. };
  33938. var scene = this.getScene();
  33939. if (scene) {
  33940. scene._loadFile(this.url, callback);
  33941. }
  33942. else {
  33943. this._engine._loadFile(this.url, callback);
  33944. }
  33945. return this._texture;
  33946. };
  33947. /**
  33948. * Starts the loading process of the texture.
  33949. */
  33950. ColorGradingTexture.prototype.loadTexture = function () {
  33951. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33952. this.load3dlTexture();
  33953. }
  33954. };
  33955. /**
  33956. * Clones the color gradind texture.
  33957. */
  33958. ColorGradingTexture.prototype.clone = function () {
  33959. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33960. // Base texture
  33961. newTexture.level = this.level;
  33962. return newTexture;
  33963. };
  33964. /**
  33965. * Called during delayed load for textures.
  33966. */
  33967. ColorGradingTexture.prototype.delayLoad = function () {
  33968. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33969. return;
  33970. }
  33971. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33972. this._texture = this._getFromCache(this.url, true);
  33973. if (!this._texture) {
  33974. this.loadTexture();
  33975. }
  33976. };
  33977. /**
  33978. * Parses a color grading texture serialized by Babylon.
  33979. * @param parsedTexture The texture information being parsedTexture
  33980. * @param scene The scene to load the texture in
  33981. * @param rootUrl The root url of the data assets to load
  33982. * @return A color gradind texture
  33983. */
  33984. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33985. var texture = null;
  33986. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33987. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33988. texture.name = parsedTexture.name;
  33989. texture.level = parsedTexture.level;
  33990. }
  33991. return texture;
  33992. };
  33993. /**
  33994. * Serializes the LUT texture to json format.
  33995. */
  33996. ColorGradingTexture.prototype.serialize = function () {
  33997. if (!this.name) {
  33998. return null;
  33999. }
  34000. var serializationObject = {};
  34001. serializationObject.name = this.name;
  34002. serializationObject.level = this.level;
  34003. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34004. return serializationObject;
  34005. };
  34006. /**
  34007. * Empty line regex stored for GC.
  34008. */
  34009. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34010. return ColorGradingTexture;
  34011. }(BABYLON.BaseTexture));
  34012. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34013. })(BABYLON || (BABYLON = {}));
  34014. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34015. var BABYLON;
  34016. (function (BABYLON) {
  34017. /**
  34018. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34019. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34020. * 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;
  34021. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34022. */
  34023. var ColorCurves = /** @class */ (function () {
  34024. function ColorCurves() {
  34025. this._dirty = true;
  34026. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34027. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34028. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34029. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34030. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34031. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34032. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34033. this._globalHue = 30;
  34034. this._globalDensity = 0;
  34035. this._globalSaturation = 0;
  34036. this._globalExposure = 0;
  34037. this._highlightsHue = 30;
  34038. this._highlightsDensity = 0;
  34039. this._highlightsSaturation = 0;
  34040. this._highlightsExposure = 0;
  34041. this._midtonesHue = 30;
  34042. this._midtonesDensity = 0;
  34043. this._midtonesSaturation = 0;
  34044. this._midtonesExposure = 0;
  34045. this._shadowsHue = 30;
  34046. this._shadowsDensity = 0;
  34047. this._shadowsSaturation = 0;
  34048. this._shadowsExposure = 0;
  34049. }
  34050. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34051. /**
  34052. * Gets the global Hue value.
  34053. * 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).
  34054. */
  34055. get: function () {
  34056. return this._globalHue;
  34057. },
  34058. /**
  34059. * Sets the global Hue value.
  34060. * 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).
  34061. */
  34062. set: function (value) {
  34063. this._globalHue = value;
  34064. this._dirty = true;
  34065. },
  34066. enumerable: true,
  34067. configurable: true
  34068. });
  34069. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34070. /**
  34071. * Gets the global Density value.
  34072. * 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.
  34073. * Values less than zero provide a filter of opposite hue.
  34074. */
  34075. get: function () {
  34076. return this._globalDensity;
  34077. },
  34078. /**
  34079. * Sets the global Density value.
  34080. * 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.
  34081. * Values less than zero provide a filter of opposite hue.
  34082. */
  34083. set: function (value) {
  34084. this._globalDensity = value;
  34085. this._dirty = true;
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34091. /**
  34092. * Gets the global Saturation value.
  34093. * 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.
  34094. */
  34095. get: function () {
  34096. return this._globalSaturation;
  34097. },
  34098. /**
  34099. * Sets the global Saturation value.
  34100. * 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.
  34101. */
  34102. set: function (value) {
  34103. this._globalSaturation = value;
  34104. this._dirty = true;
  34105. },
  34106. enumerable: true,
  34107. configurable: true
  34108. });
  34109. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34110. /**
  34111. * Gets the highlights Hue value.
  34112. * 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).
  34113. */
  34114. get: function () {
  34115. return this._highlightsHue;
  34116. },
  34117. /**
  34118. * Sets the highlights Hue value.
  34119. * 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).
  34120. */
  34121. set: function (value) {
  34122. this._highlightsHue = value;
  34123. this._dirty = true;
  34124. },
  34125. enumerable: true,
  34126. configurable: true
  34127. });
  34128. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34129. /**
  34130. * Gets the highlights Density value.
  34131. * 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.
  34132. * Values less than zero provide a filter of opposite hue.
  34133. */
  34134. get: function () {
  34135. return this._highlightsDensity;
  34136. },
  34137. /**
  34138. * Sets the highlights Density value.
  34139. * 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.
  34140. * Values less than zero provide a filter of opposite hue.
  34141. */
  34142. set: function (value) {
  34143. this._highlightsDensity = value;
  34144. this._dirty = true;
  34145. },
  34146. enumerable: true,
  34147. configurable: true
  34148. });
  34149. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34150. /**
  34151. * Gets the highlights Saturation value.
  34152. * 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.
  34153. */
  34154. get: function () {
  34155. return this._highlightsSaturation;
  34156. },
  34157. /**
  34158. * Sets the highlights Saturation value.
  34159. * 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.
  34160. */
  34161. set: function (value) {
  34162. this._highlightsSaturation = value;
  34163. this._dirty = true;
  34164. },
  34165. enumerable: true,
  34166. configurable: true
  34167. });
  34168. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34169. /**
  34170. * Gets the highlights Exposure value.
  34171. * 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.
  34172. */
  34173. get: function () {
  34174. return this._highlightsExposure;
  34175. },
  34176. /**
  34177. * Sets the highlights Exposure value.
  34178. * 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.
  34179. */
  34180. set: function (value) {
  34181. this._highlightsExposure = value;
  34182. this._dirty = true;
  34183. },
  34184. enumerable: true,
  34185. configurable: true
  34186. });
  34187. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34188. /**
  34189. * Gets the midtones Hue value.
  34190. * 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).
  34191. */
  34192. get: function () {
  34193. return this._midtonesHue;
  34194. },
  34195. /**
  34196. * Sets the midtones Hue value.
  34197. * 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).
  34198. */
  34199. set: function (value) {
  34200. this._midtonesHue = value;
  34201. this._dirty = true;
  34202. },
  34203. enumerable: true,
  34204. configurable: true
  34205. });
  34206. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34207. /**
  34208. * Gets the midtones Density value.
  34209. * 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.
  34210. * Values less than zero provide a filter of opposite hue.
  34211. */
  34212. get: function () {
  34213. return this._midtonesDensity;
  34214. },
  34215. /**
  34216. * Sets the midtones Density value.
  34217. * 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.
  34218. * Values less than zero provide a filter of opposite hue.
  34219. */
  34220. set: function (value) {
  34221. this._midtonesDensity = value;
  34222. this._dirty = true;
  34223. },
  34224. enumerable: true,
  34225. configurable: true
  34226. });
  34227. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34228. /**
  34229. * Gets the midtones Saturation value.
  34230. * 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.
  34231. */
  34232. get: function () {
  34233. return this._midtonesSaturation;
  34234. },
  34235. /**
  34236. * Sets the midtones Saturation value.
  34237. * 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.
  34238. */
  34239. set: function (value) {
  34240. this._midtonesSaturation = value;
  34241. this._dirty = true;
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34247. /**
  34248. * Gets the midtones Exposure value.
  34249. * 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.
  34250. */
  34251. get: function () {
  34252. return this._midtonesExposure;
  34253. },
  34254. /**
  34255. * Sets the midtones Exposure value.
  34256. * 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.
  34257. */
  34258. set: function (value) {
  34259. this._midtonesExposure = value;
  34260. this._dirty = true;
  34261. },
  34262. enumerable: true,
  34263. configurable: true
  34264. });
  34265. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34266. /**
  34267. * Gets the shadows Hue value.
  34268. * 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).
  34269. */
  34270. get: function () {
  34271. return this._shadowsHue;
  34272. },
  34273. /**
  34274. * Sets the shadows Hue value.
  34275. * 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).
  34276. */
  34277. set: function (value) {
  34278. this._shadowsHue = value;
  34279. this._dirty = true;
  34280. },
  34281. enumerable: true,
  34282. configurable: true
  34283. });
  34284. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34285. /**
  34286. * Gets the shadows Density value.
  34287. * 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.
  34288. * Values less than zero provide a filter of opposite hue.
  34289. */
  34290. get: function () {
  34291. return this._shadowsDensity;
  34292. },
  34293. /**
  34294. * Sets the shadows Density value.
  34295. * 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.
  34296. * Values less than zero provide a filter of opposite hue.
  34297. */
  34298. set: function (value) {
  34299. this._shadowsDensity = value;
  34300. this._dirty = true;
  34301. },
  34302. enumerable: true,
  34303. configurable: true
  34304. });
  34305. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34306. /**
  34307. * Gets the shadows Saturation value.
  34308. * 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.
  34309. */
  34310. get: function () {
  34311. return this._shadowsSaturation;
  34312. },
  34313. /**
  34314. * Sets the shadows Saturation value.
  34315. * 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.
  34316. */
  34317. set: function (value) {
  34318. this._shadowsSaturation = value;
  34319. this._dirty = true;
  34320. },
  34321. enumerable: true,
  34322. configurable: true
  34323. });
  34324. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34325. /**
  34326. * Gets the shadows Exposure value.
  34327. * 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.
  34328. */
  34329. get: function () {
  34330. return this._shadowsExposure;
  34331. },
  34332. /**
  34333. * Sets the shadows Exposure value.
  34334. * 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.
  34335. */
  34336. set: function (value) {
  34337. this._shadowsExposure = value;
  34338. this._dirty = true;
  34339. },
  34340. enumerable: true,
  34341. configurable: true
  34342. });
  34343. ColorCurves.prototype.getClassName = function () {
  34344. return "ColorCurves";
  34345. };
  34346. /**
  34347. * Binds the color curves to the shader.
  34348. * @param colorCurves The color curve to bind
  34349. * @param effect The effect to bind to
  34350. */
  34351. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34352. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34353. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34354. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34355. if (colorCurves._dirty) {
  34356. colorCurves._dirty = false;
  34357. // Fill in global info.
  34358. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34359. // Compute highlights info.
  34360. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34361. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34362. // Compute midtones info.
  34363. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34364. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34365. // Compute shadows info.
  34366. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34367. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34368. // Compute deltas (neutral is midtones).
  34369. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34370. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34371. }
  34372. if (effect) {
  34373. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34374. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34375. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34376. }
  34377. };
  34378. /**
  34379. * Prepare the list of uniforms associated with the ColorCurves effects.
  34380. * @param uniformsList The list of uniforms used in the effect
  34381. */
  34382. ColorCurves.PrepareUniforms = function (uniformsList) {
  34383. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34384. };
  34385. /**
  34386. * Returns color grading data based on a hue, density, saturation and exposure value.
  34387. * @param filterHue The hue of the color filter.
  34388. * @param filterDensity The density of the color filter.
  34389. * @param saturation The saturation.
  34390. * @param exposure The exposure.
  34391. * @param result The result data container.
  34392. */
  34393. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34394. if (hue == null) {
  34395. return;
  34396. }
  34397. hue = ColorCurves.clamp(hue, 0, 360);
  34398. density = ColorCurves.clamp(density, -100, 100);
  34399. saturation = ColorCurves.clamp(saturation, -100, 100);
  34400. exposure = ColorCurves.clamp(exposure, -100, 100);
  34401. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34402. // so that the maximum filter density is only 50% control. This provides fine control
  34403. // for small values and reasonable range.
  34404. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34405. density *= 0.5;
  34406. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34407. if (density < 0) {
  34408. density *= -1;
  34409. hue = (hue + 180) % 360;
  34410. }
  34411. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34412. result.scaleToRef(2, result);
  34413. result.a = 1 + 0.01 * saturation;
  34414. };
  34415. /**
  34416. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34417. * @param value The input slider value in range [-100,100].
  34418. * @returns Adjusted value.
  34419. */
  34420. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34421. value /= 100;
  34422. var x = Math.abs(value);
  34423. x = Math.pow(x, 2);
  34424. if (value < 0) {
  34425. x *= -1;
  34426. }
  34427. x *= 100;
  34428. return x;
  34429. };
  34430. /**
  34431. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34432. * @param hue The hue (H) input.
  34433. * @param saturation The saturation (S) input.
  34434. * @param brightness The brightness (B) input.
  34435. * @result An RGBA color represented as Vector4.
  34436. */
  34437. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34438. var h = ColorCurves.clamp(hue, 0, 360);
  34439. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34440. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34441. if (s === 0) {
  34442. result.r = v;
  34443. result.g = v;
  34444. result.b = v;
  34445. }
  34446. else {
  34447. // sector 0 to 5
  34448. h /= 60;
  34449. var i = Math.floor(h);
  34450. // fractional part of h
  34451. var f = h - i;
  34452. var p = v * (1 - s);
  34453. var q = v * (1 - s * f);
  34454. var t = v * (1 - s * (1 - f));
  34455. switch (i) {
  34456. case 0:
  34457. result.r = v;
  34458. result.g = t;
  34459. result.b = p;
  34460. break;
  34461. case 1:
  34462. result.r = q;
  34463. result.g = v;
  34464. result.b = p;
  34465. break;
  34466. case 2:
  34467. result.r = p;
  34468. result.g = v;
  34469. result.b = t;
  34470. break;
  34471. case 3:
  34472. result.r = p;
  34473. result.g = q;
  34474. result.b = v;
  34475. break;
  34476. case 4:
  34477. result.r = t;
  34478. result.g = p;
  34479. result.b = v;
  34480. break;
  34481. default:// case 5:
  34482. result.r = v;
  34483. result.g = p;
  34484. result.b = q;
  34485. break;
  34486. }
  34487. }
  34488. result.a = 1;
  34489. };
  34490. /**
  34491. * Returns a value clamped between min and max
  34492. * @param value The value to clamp
  34493. * @param min The minimum of value
  34494. * @param max The maximum of value
  34495. * @returns The clamped value.
  34496. */
  34497. ColorCurves.clamp = function (value, min, max) {
  34498. return Math.min(Math.max(value, min), max);
  34499. };
  34500. /**
  34501. * Clones the current color curve instance.
  34502. * @return The cloned curves
  34503. */
  34504. ColorCurves.prototype.clone = function () {
  34505. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34506. };
  34507. /**
  34508. * Serializes the current color curve instance to a json representation.
  34509. * @return a JSON representation
  34510. */
  34511. ColorCurves.prototype.serialize = function () {
  34512. return BABYLON.SerializationHelper.Serialize(this);
  34513. };
  34514. /**
  34515. * Parses the color curve from a json representation.
  34516. * @param source the JSON source to parse
  34517. * @return The parsed curves
  34518. */
  34519. ColorCurves.Parse = function (source) {
  34520. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34521. };
  34522. __decorate([
  34523. BABYLON.serialize()
  34524. ], ColorCurves.prototype, "_globalHue", void 0);
  34525. __decorate([
  34526. BABYLON.serialize()
  34527. ], ColorCurves.prototype, "_globalDensity", void 0);
  34528. __decorate([
  34529. BABYLON.serialize()
  34530. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34531. __decorate([
  34532. BABYLON.serialize()
  34533. ], ColorCurves.prototype, "_globalExposure", void 0);
  34534. __decorate([
  34535. BABYLON.serialize()
  34536. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34537. __decorate([
  34538. BABYLON.serialize()
  34539. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34540. __decorate([
  34541. BABYLON.serialize()
  34542. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34543. __decorate([
  34544. BABYLON.serialize()
  34545. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34546. __decorate([
  34547. BABYLON.serialize()
  34548. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34549. __decorate([
  34550. BABYLON.serialize()
  34551. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34552. __decorate([
  34553. BABYLON.serialize()
  34554. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34555. __decorate([
  34556. BABYLON.serialize()
  34557. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34558. return ColorCurves;
  34559. }());
  34560. BABYLON.ColorCurves = ColorCurves;
  34561. })(BABYLON || (BABYLON = {}));
  34562. //# sourceMappingURL=babylon.colorCurves.js.map
  34563. //# sourceMappingURL=babylon.behavior.js.map
  34564. var BABYLON;
  34565. (function (BABYLON) {
  34566. var MaterialHelper = /** @class */ (function () {
  34567. function MaterialHelper() {
  34568. }
  34569. MaterialHelper.BindEyePosition = function (effect, scene) {
  34570. if (scene._forcedViewPosition) {
  34571. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34572. return;
  34573. }
  34574. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34575. };
  34576. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34577. defines._needUVs = true;
  34578. defines[key] = true;
  34579. if (texture.getTextureMatrix().isIdentity(true)) {
  34580. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34581. if (texture.coordinatesIndex === 0) {
  34582. defines["MAINUV1"] = true;
  34583. }
  34584. else {
  34585. defines["MAINUV2"] = true;
  34586. }
  34587. }
  34588. else {
  34589. defines[key + "DIRECTUV"] = 0;
  34590. }
  34591. };
  34592. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34593. var matrix = texture.getTextureMatrix();
  34594. if (!matrix.isIdentity(true)) {
  34595. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34596. }
  34597. };
  34598. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34599. if (defines._areMiscDirty) {
  34600. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34601. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34602. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34603. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34604. }
  34605. };
  34606. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34607. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34608. var changed = false;
  34609. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34610. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34611. changed = true;
  34612. }
  34613. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34614. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34615. changed = true;
  34616. }
  34617. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34618. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34619. changed = true;
  34620. }
  34621. if (defines["INSTANCES"] !== useInstances) {
  34622. defines["INSTANCES"] = useInstances;
  34623. changed = true;
  34624. }
  34625. if (changed) {
  34626. defines.markAsUnprocessed();
  34627. }
  34628. };
  34629. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34630. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34631. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34632. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34633. return false;
  34634. }
  34635. defines._normals = defines._needNormals;
  34636. defines._uvs = defines._needUVs;
  34637. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34638. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34639. defines["TANGENT"] = true;
  34640. }
  34641. if (defines._needUVs) {
  34642. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34643. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34644. }
  34645. else {
  34646. defines["UV1"] = false;
  34647. defines["UV2"] = false;
  34648. }
  34649. if (useVertexColor) {
  34650. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34651. defines["VERTEXCOLOR"] = hasVertexColors;
  34652. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34653. }
  34654. if (useBones) {
  34655. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34656. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34657. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34658. }
  34659. else {
  34660. defines["NUM_BONE_INFLUENCERS"] = 0;
  34661. defines["BonesPerMesh"] = 0;
  34662. }
  34663. }
  34664. if (useMorphTargets) {
  34665. var manager = mesh.morphTargetManager;
  34666. if (manager) {
  34667. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34668. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34669. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34670. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34671. }
  34672. else {
  34673. defines["MORPHTARGETS_TANGENT"] = false;
  34674. defines["MORPHTARGETS_NORMAL"] = false;
  34675. defines["MORPHTARGETS"] = false;
  34676. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34677. }
  34678. }
  34679. return true;
  34680. };
  34681. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34682. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34683. if (disableLighting === void 0) { disableLighting = false; }
  34684. if (!defines._areLightsDirty) {
  34685. return defines._needNormals;
  34686. }
  34687. var lightIndex = 0;
  34688. var needNormals = false;
  34689. var needRebuild = false;
  34690. var lightmapMode = false;
  34691. var shadowEnabled = false;
  34692. var specularEnabled = false;
  34693. if (scene.lightsEnabled && !disableLighting) {
  34694. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34695. var light = _a[_i];
  34696. needNormals = true;
  34697. if (defines["LIGHT" + lightIndex] === undefined) {
  34698. needRebuild = true;
  34699. }
  34700. defines["LIGHT" + lightIndex] = true;
  34701. defines["SPOTLIGHT" + lightIndex] = false;
  34702. defines["HEMILIGHT" + lightIndex] = false;
  34703. defines["POINTLIGHT" + lightIndex] = false;
  34704. defines["DIRLIGHT" + lightIndex] = false;
  34705. var type;
  34706. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34707. type = "SPOTLIGHT" + lightIndex;
  34708. }
  34709. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34710. type = "HEMILIGHT" + lightIndex;
  34711. }
  34712. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34713. type = "POINTLIGHT" + lightIndex;
  34714. }
  34715. else {
  34716. type = "DIRLIGHT" + lightIndex;
  34717. }
  34718. defines[type] = true;
  34719. // Specular
  34720. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34721. specularEnabled = true;
  34722. }
  34723. // Shadows
  34724. defines["SHADOW" + lightIndex] = false;
  34725. defines["SHADOWPCF" + lightIndex] = false;
  34726. defines["SHADOWESM" + lightIndex] = false;
  34727. defines["SHADOWCUBE" + lightIndex] = false;
  34728. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34729. var shadowGenerator = light.getShadowGenerator();
  34730. if (shadowGenerator) {
  34731. shadowEnabled = true;
  34732. shadowGenerator.prepareDefines(defines, lightIndex);
  34733. }
  34734. }
  34735. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34736. lightmapMode = true;
  34737. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34738. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34739. }
  34740. else {
  34741. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34742. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34743. }
  34744. lightIndex++;
  34745. if (lightIndex === maxSimultaneousLights)
  34746. break;
  34747. }
  34748. }
  34749. defines["SPECULARTERM"] = specularEnabled;
  34750. defines["SHADOWS"] = shadowEnabled;
  34751. // Resetting all other lights if any
  34752. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34753. if (defines["LIGHT" + index] !== undefined) {
  34754. defines["LIGHT" + index] = false;
  34755. defines["HEMILIGHT" + lightIndex] = false;
  34756. defines["POINTLIGHT" + lightIndex] = false;
  34757. defines["DIRLIGHT" + lightIndex] = false;
  34758. defines["SPOTLIGHT" + lightIndex] = false;
  34759. defines["SHADOW" + lightIndex] = false;
  34760. }
  34761. }
  34762. var caps = scene.getEngine().getCaps();
  34763. if (defines["SHADOWFLOAT"] === undefined) {
  34764. needRebuild = true;
  34765. }
  34766. defines["SHADOWFLOAT"] = shadowEnabled &&
  34767. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34768. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34769. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34770. if (needRebuild) {
  34771. defines.rebuild();
  34772. }
  34773. return needNormals;
  34774. };
  34775. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34776. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34777. var uniformsList;
  34778. var uniformBuffersList = null;
  34779. if (uniformsListOrOptions.uniformsNames) {
  34780. var options = uniformsListOrOptions;
  34781. uniformsList = options.uniformsNames;
  34782. uniformBuffersList = options.uniformBuffersNames;
  34783. samplersList = options.samplers;
  34784. defines = options.defines;
  34785. maxSimultaneousLights = options.maxSimultaneousLights;
  34786. }
  34787. else {
  34788. uniformsList = uniformsListOrOptions;
  34789. if (!samplersList) {
  34790. samplersList = [];
  34791. }
  34792. }
  34793. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34794. if (!defines["LIGHT" + lightIndex]) {
  34795. break;
  34796. }
  34797. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34798. if (uniformBuffersList) {
  34799. uniformBuffersList.push("Light" + lightIndex);
  34800. }
  34801. samplersList.push("shadowSampler" + lightIndex);
  34802. }
  34803. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34804. uniformsList.push("morphTargetInfluences");
  34805. }
  34806. };
  34807. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34808. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34809. if (rank === void 0) { rank = 0; }
  34810. var lightFallbackRank = 0;
  34811. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34812. if (!defines["LIGHT" + lightIndex]) {
  34813. break;
  34814. }
  34815. if (lightIndex > 0) {
  34816. lightFallbackRank = rank + lightIndex;
  34817. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34818. }
  34819. if (!defines["SHADOWS"]) {
  34820. if (defines["SHADOW" + lightIndex]) {
  34821. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34822. }
  34823. if (defines["SHADOWPCF" + lightIndex]) {
  34824. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34825. }
  34826. if (defines["SHADOWESM" + lightIndex]) {
  34827. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34828. }
  34829. }
  34830. }
  34831. return lightFallbackRank++;
  34832. };
  34833. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34834. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34835. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34836. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34837. var manager = mesh.morphTargetManager;
  34838. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34839. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34840. for (var index = 0; index < influencers; index++) {
  34841. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34842. if (normal) {
  34843. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34844. }
  34845. if (tangent) {
  34846. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34847. }
  34848. if (attribs.length > maxAttributesCount) {
  34849. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34850. }
  34851. }
  34852. }
  34853. };
  34854. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34855. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34856. fallbacks.addCPUSkinningFallback(0, mesh);
  34857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34859. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34860. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34861. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34862. }
  34863. }
  34864. };
  34865. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34866. if (defines["INSTANCES"]) {
  34867. attribs.push("world0");
  34868. attribs.push("world1");
  34869. attribs.push("world2");
  34870. attribs.push("world3");
  34871. }
  34872. };
  34873. // Bindings
  34874. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34875. if (light.shadowEnabled && mesh.receiveShadows) {
  34876. var shadowGenerator = light.getShadowGenerator();
  34877. if (shadowGenerator) {
  34878. shadowGenerator.bindShadowLight(lightIndex, effect);
  34879. }
  34880. }
  34881. };
  34882. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34883. light.transferToEffect(effect, lightIndex + "");
  34884. };
  34885. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34886. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34887. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34888. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34889. for (var i = 0; i < len; i++) {
  34890. var light = mesh._lightSources[i];
  34891. var iAsString = i.toString();
  34892. var scaledIntensity = light.getScaledIntensity();
  34893. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34894. MaterialHelper.BindLightProperties(light, effect, i);
  34895. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34896. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34897. if (defines["SPECULARTERM"]) {
  34898. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34899. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34900. }
  34901. // Shadows
  34902. if (scene.shadowsEnabled) {
  34903. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34904. }
  34905. light._uniformBuffer.update();
  34906. }
  34907. };
  34908. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34909. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34910. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34911. effect.setColor3("vFogColor", scene.fogColor);
  34912. }
  34913. };
  34914. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34915. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34916. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34917. if (matrices && effect) {
  34918. effect.setMatrices("mBones", matrices);
  34919. }
  34920. }
  34921. };
  34922. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34923. var manager = abstractMesh.morphTargetManager;
  34924. if (!abstractMesh || !manager) {
  34925. return;
  34926. }
  34927. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34928. };
  34929. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34930. if (defines["LOGARITHMICDEPTH"]) {
  34931. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34932. }
  34933. };
  34934. MaterialHelper.BindClipPlane = function (effect, scene) {
  34935. if (scene.clipPlane) {
  34936. var clipPlane = scene.clipPlane;
  34937. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34938. }
  34939. };
  34940. return MaterialHelper;
  34941. }());
  34942. BABYLON.MaterialHelper = MaterialHelper;
  34943. })(BABYLON || (BABYLON = {}));
  34944. //# sourceMappingURL=babylon.materialHelper.js.map
  34945. var BABYLON;
  34946. (function (BABYLON) {
  34947. var PushMaterial = /** @class */ (function (_super) {
  34948. __extends(PushMaterial, _super);
  34949. function PushMaterial(name, scene) {
  34950. var _this = _super.call(this, name, scene) || this;
  34951. _this.storeEffectOnSubMeshes = true;
  34952. return _this;
  34953. }
  34954. PushMaterial.prototype.getEffect = function () {
  34955. return this._activeEffect;
  34956. };
  34957. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34958. if (!mesh) {
  34959. return false;
  34960. }
  34961. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34962. return true;
  34963. }
  34964. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34965. };
  34966. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34967. this._activeEffect.setMatrix("world", world);
  34968. };
  34969. PushMaterial.prototype.bind = function (world, mesh) {
  34970. if (!mesh) {
  34971. return;
  34972. }
  34973. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34974. };
  34975. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34976. if (effect === void 0) { effect = null; }
  34977. _super.prototype._afterBind.call(this, mesh);
  34978. this.getScene()._cachedEffect = effect;
  34979. };
  34980. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34981. if (visibility === void 0) { visibility = 1; }
  34982. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34983. };
  34984. return PushMaterial;
  34985. }(BABYLON.Material));
  34986. BABYLON.PushMaterial = PushMaterial;
  34987. })(BABYLON || (BABYLON = {}));
  34988. //# sourceMappingURL=babylon.pushMaterial.js.map
  34989. var BABYLON;
  34990. (function (BABYLON) {
  34991. var StandardMaterialDefines = /** @class */ (function (_super) {
  34992. __extends(StandardMaterialDefines, _super);
  34993. function StandardMaterialDefines() {
  34994. var _this = _super.call(this) || this;
  34995. _this.MAINUV1 = false;
  34996. _this.MAINUV2 = false;
  34997. _this.DIFFUSE = false;
  34998. _this.DIFFUSEDIRECTUV = 0;
  34999. _this.AMBIENT = false;
  35000. _this.AMBIENTDIRECTUV = 0;
  35001. _this.OPACITY = false;
  35002. _this.OPACITYDIRECTUV = 0;
  35003. _this.OPACITYRGB = false;
  35004. _this.REFLECTION = false;
  35005. _this.EMISSIVE = false;
  35006. _this.EMISSIVEDIRECTUV = 0;
  35007. _this.SPECULAR = false;
  35008. _this.SPECULARDIRECTUV = 0;
  35009. _this.BUMP = false;
  35010. _this.BUMPDIRECTUV = 0;
  35011. _this.PARALLAX = false;
  35012. _this.PARALLAXOCCLUSION = false;
  35013. _this.SPECULAROVERALPHA = false;
  35014. _this.CLIPPLANE = false;
  35015. _this.ALPHATEST = false;
  35016. _this.DEPTHPREPASS = false;
  35017. _this.ALPHAFROMDIFFUSE = false;
  35018. _this.POINTSIZE = false;
  35019. _this.FOG = false;
  35020. _this.SPECULARTERM = false;
  35021. _this.DIFFUSEFRESNEL = false;
  35022. _this.OPACITYFRESNEL = false;
  35023. _this.REFLECTIONFRESNEL = false;
  35024. _this.REFRACTIONFRESNEL = false;
  35025. _this.EMISSIVEFRESNEL = false;
  35026. _this.FRESNEL = false;
  35027. _this.NORMAL = false;
  35028. _this.UV1 = false;
  35029. _this.UV2 = false;
  35030. _this.VERTEXCOLOR = false;
  35031. _this.VERTEXALPHA = false;
  35032. _this.NUM_BONE_INFLUENCERS = 0;
  35033. _this.BonesPerMesh = 0;
  35034. _this.INSTANCES = false;
  35035. _this.GLOSSINESS = false;
  35036. _this.ROUGHNESS = false;
  35037. _this.EMISSIVEASILLUMINATION = false;
  35038. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35039. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35040. _this.LIGHTMAP = false;
  35041. _this.LIGHTMAPDIRECTUV = 0;
  35042. _this.USELIGHTMAPASSHADOWMAP = false;
  35043. _this.REFLECTIONMAP_3D = false;
  35044. _this.REFLECTIONMAP_SPHERICAL = false;
  35045. _this.REFLECTIONMAP_PLANAR = false;
  35046. _this.REFLECTIONMAP_CUBIC = false;
  35047. _this.REFLECTIONMAP_PROJECTION = false;
  35048. _this.REFLECTIONMAP_SKYBOX = false;
  35049. _this.REFLECTIONMAP_EXPLICIT = false;
  35050. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35051. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35052. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35053. _this.INVERTCUBICMAP = false;
  35054. _this.LOGARITHMICDEPTH = false;
  35055. _this.REFRACTION = false;
  35056. _this.REFRACTIONMAP_3D = false;
  35057. _this.REFLECTIONOVERALPHA = false;
  35058. _this.TWOSIDEDLIGHTING = false;
  35059. _this.SHADOWFLOAT = false;
  35060. _this.MORPHTARGETS = false;
  35061. _this.MORPHTARGETS_NORMAL = false;
  35062. _this.MORPHTARGETS_TANGENT = false;
  35063. _this.NUM_MORPH_INFLUENCERS = 0;
  35064. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35065. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35066. _this.IMAGEPROCESSING = false;
  35067. _this.VIGNETTE = false;
  35068. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35069. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35070. _this.TONEMAPPING = false;
  35071. _this.CONTRAST = false;
  35072. _this.COLORCURVES = false;
  35073. _this.COLORGRADING = false;
  35074. _this.COLORGRADING3D = false;
  35075. _this.SAMPLER3DGREENDEPTH = false;
  35076. _this.SAMPLER3DBGRMAP = false;
  35077. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35078. _this.EXPOSURE = false;
  35079. _this.rebuild();
  35080. return _this;
  35081. }
  35082. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35083. var modes = [
  35084. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35085. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35086. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35087. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35088. ];
  35089. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35090. var mode = modes_1[_i];
  35091. this[mode] = (mode === modeToEnable);
  35092. }
  35093. };
  35094. return StandardMaterialDefines;
  35095. }(BABYLON.MaterialDefines));
  35096. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35097. var StandardMaterial = /** @class */ (function (_super) {
  35098. __extends(StandardMaterial, _super);
  35099. function StandardMaterial(name, scene) {
  35100. var _this = _super.call(this, name, scene) || this;
  35101. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35102. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35103. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35104. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35105. _this.specularPower = 64;
  35106. _this._useAlphaFromDiffuseTexture = false;
  35107. _this._useEmissiveAsIllumination = false;
  35108. _this._linkEmissiveWithDiffuse = false;
  35109. _this._useSpecularOverAlpha = false;
  35110. _this._useReflectionOverAlpha = false;
  35111. _this._disableLighting = false;
  35112. _this._useParallax = false;
  35113. _this._useParallaxOcclusion = false;
  35114. _this.parallaxScaleBias = 0.05;
  35115. _this._roughness = 0;
  35116. _this.indexOfRefraction = 0.98;
  35117. _this.invertRefractionY = true;
  35118. _this._useLightmapAsShadowmap = false;
  35119. _this._useReflectionFresnelFromSpecular = false;
  35120. _this._useGlossinessFromSpecularMapAlpha = false;
  35121. _this._maxSimultaneousLights = 4;
  35122. /**
  35123. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35124. */
  35125. _this._invertNormalMapX = false;
  35126. /**
  35127. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35128. */
  35129. _this._invertNormalMapY = false;
  35130. /**
  35131. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35132. */
  35133. _this._twoSidedLighting = false;
  35134. _this._renderTargets = new BABYLON.SmartArray(16);
  35135. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35136. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35137. // Setup the default processing configuration to the scene.
  35138. _this._attachImageProcessingConfiguration(null);
  35139. _this.getRenderTargetTextures = function () {
  35140. _this._renderTargets.reset();
  35141. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35142. _this._renderTargets.push(_this._reflectionTexture);
  35143. }
  35144. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35145. _this._renderTargets.push(_this._refractionTexture);
  35146. }
  35147. return _this._renderTargets;
  35148. };
  35149. return _this;
  35150. }
  35151. ;
  35152. ;
  35153. ;
  35154. ;
  35155. ;
  35156. ;
  35157. ;
  35158. ;
  35159. ;
  35160. ;
  35161. ;
  35162. ;
  35163. ;
  35164. ;
  35165. ;
  35166. ;
  35167. ;
  35168. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35169. /**
  35170. * Gets the image processing configuration used either in this material.
  35171. */
  35172. get: function () {
  35173. return this._imageProcessingConfiguration;
  35174. },
  35175. /**
  35176. * Sets the Default image processing configuration used either in the this material.
  35177. *
  35178. * If sets to null, the scene one is in use.
  35179. */
  35180. set: function (value) {
  35181. this._attachImageProcessingConfiguration(value);
  35182. // Ensure the effect will be rebuilt.
  35183. this._markAllSubMeshesAsTexturesDirty();
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. /**
  35189. * Attaches a new image processing configuration to the Standard Material.
  35190. * @param configuration
  35191. */
  35192. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35193. var _this = this;
  35194. if (configuration === this._imageProcessingConfiguration) {
  35195. return;
  35196. }
  35197. // Detaches observer.
  35198. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35199. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35200. }
  35201. // Pick the scene configuration if needed.
  35202. if (!configuration) {
  35203. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35204. }
  35205. else {
  35206. this._imageProcessingConfiguration = configuration;
  35207. }
  35208. // Attaches observer.
  35209. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35210. _this._markAllSubMeshesAsImageProcessingDirty();
  35211. });
  35212. };
  35213. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35214. /**
  35215. * Gets wether the color curves effect is enabled.
  35216. */
  35217. get: function () {
  35218. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35219. },
  35220. /**
  35221. * Sets wether the color curves effect is enabled.
  35222. */
  35223. set: function (value) {
  35224. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35230. /**
  35231. * Gets wether the color grading effect is enabled.
  35232. */
  35233. get: function () {
  35234. return this.imageProcessingConfiguration.colorGradingEnabled;
  35235. },
  35236. /**
  35237. * Gets wether the color grading effect is enabled.
  35238. */
  35239. set: function (value) {
  35240. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35241. },
  35242. enumerable: true,
  35243. configurable: true
  35244. });
  35245. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35246. /**
  35247. * Gets wether tonemapping is enabled or not.
  35248. */
  35249. get: function () {
  35250. return this._imageProcessingConfiguration.toneMappingEnabled;
  35251. },
  35252. /**
  35253. * Sets wether tonemapping is enabled or not
  35254. */
  35255. set: function (value) {
  35256. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35257. },
  35258. enumerable: true,
  35259. configurable: true
  35260. });
  35261. ;
  35262. ;
  35263. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35264. /**
  35265. * The camera exposure used on this material.
  35266. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35267. * This corresponds to a photographic exposure.
  35268. */
  35269. get: function () {
  35270. return this._imageProcessingConfiguration.exposure;
  35271. },
  35272. /**
  35273. * The camera exposure used on this material.
  35274. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35275. * This corresponds to a photographic exposure.
  35276. */
  35277. set: function (value) {
  35278. this._imageProcessingConfiguration.exposure = value;
  35279. },
  35280. enumerable: true,
  35281. configurable: true
  35282. });
  35283. ;
  35284. ;
  35285. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35286. /**
  35287. * Gets The camera contrast used on this material.
  35288. */
  35289. get: function () {
  35290. return this._imageProcessingConfiguration.contrast;
  35291. },
  35292. /**
  35293. * Sets The camera contrast used on this material.
  35294. */
  35295. set: function (value) {
  35296. this._imageProcessingConfiguration.contrast = value;
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35302. /**
  35303. * Gets the Color Grading 2D Lookup Texture.
  35304. */
  35305. get: function () {
  35306. return this._imageProcessingConfiguration.colorGradingTexture;
  35307. },
  35308. /**
  35309. * Sets the Color Grading 2D Lookup Texture.
  35310. */
  35311. set: function (value) {
  35312. this._imageProcessingConfiguration.colorGradingTexture = value;
  35313. },
  35314. enumerable: true,
  35315. configurable: true
  35316. });
  35317. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35318. /**
  35319. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35320. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35321. * 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;
  35322. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35323. */
  35324. get: function () {
  35325. return this._imageProcessingConfiguration.colorCurves;
  35326. },
  35327. /**
  35328. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35329. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35330. * 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;
  35331. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35332. */
  35333. set: function (value) {
  35334. this._imageProcessingConfiguration.colorCurves = value;
  35335. },
  35336. enumerable: true,
  35337. configurable: true
  35338. });
  35339. StandardMaterial.prototype.getClassName = function () {
  35340. return "StandardMaterial";
  35341. };
  35342. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35343. get: function () {
  35344. return this._useLogarithmicDepth;
  35345. },
  35346. set: function (value) {
  35347. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35348. this._markAllSubMeshesAsMiscDirty();
  35349. },
  35350. enumerable: true,
  35351. configurable: true
  35352. });
  35353. StandardMaterial.prototype.needAlphaBlending = function () {
  35354. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35355. };
  35356. StandardMaterial.prototype.needAlphaTesting = function () {
  35357. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35358. };
  35359. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35360. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35361. };
  35362. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35363. return this._diffuseTexture;
  35364. };
  35365. /**
  35366. * Child classes can use it to update shaders
  35367. */
  35368. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35369. if (useInstances === void 0) { useInstances = false; }
  35370. if (subMesh.effect && this.isFrozen) {
  35371. if (this._wasPreviouslyReady && subMesh.effect) {
  35372. return true;
  35373. }
  35374. }
  35375. if (!subMesh._materialDefines) {
  35376. subMesh._materialDefines = new StandardMaterialDefines();
  35377. }
  35378. var scene = this.getScene();
  35379. var defines = subMesh._materialDefines;
  35380. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35381. if (defines._renderId === scene.getRenderId()) {
  35382. return true;
  35383. }
  35384. }
  35385. var engine = scene.getEngine();
  35386. // Lights
  35387. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35388. // Textures
  35389. if (defines._areTexturesDirty) {
  35390. defines._needUVs = false;
  35391. defines.MAINUV1 = false;
  35392. defines.MAINUV2 = false;
  35393. if (scene.texturesEnabled) {
  35394. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35395. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35396. return false;
  35397. }
  35398. else {
  35399. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35400. }
  35401. }
  35402. else {
  35403. defines.DIFFUSE = false;
  35404. }
  35405. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35406. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35407. return false;
  35408. }
  35409. else {
  35410. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35411. }
  35412. }
  35413. else {
  35414. defines.AMBIENT = false;
  35415. }
  35416. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35417. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35418. return false;
  35419. }
  35420. else {
  35421. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35422. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35423. }
  35424. }
  35425. else {
  35426. defines.OPACITY = false;
  35427. }
  35428. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35429. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35430. return false;
  35431. }
  35432. else {
  35433. defines._needNormals = true;
  35434. defines.REFLECTION = true;
  35435. defines.ROUGHNESS = (this._roughness > 0);
  35436. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35437. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35438. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35439. switch (this._reflectionTexture.coordinatesMode) {
  35440. case BABYLON.Texture.CUBIC_MODE:
  35441. case BABYLON.Texture.INVCUBIC_MODE:
  35442. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35443. break;
  35444. case BABYLON.Texture.EXPLICIT_MODE:
  35445. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35446. break;
  35447. case BABYLON.Texture.PLANAR_MODE:
  35448. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35449. break;
  35450. case BABYLON.Texture.PROJECTION_MODE:
  35451. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35452. break;
  35453. case BABYLON.Texture.SKYBOX_MODE:
  35454. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35455. break;
  35456. case BABYLON.Texture.SPHERICAL_MODE:
  35457. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35458. break;
  35459. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35460. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35461. break;
  35462. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35463. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35464. break;
  35465. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35466. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35467. break;
  35468. }
  35469. }
  35470. }
  35471. else {
  35472. defines.REFLECTION = false;
  35473. }
  35474. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35475. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35476. return false;
  35477. }
  35478. else {
  35479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35480. }
  35481. }
  35482. else {
  35483. defines.EMISSIVE = false;
  35484. }
  35485. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35486. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35487. return false;
  35488. }
  35489. else {
  35490. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35491. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35492. }
  35493. }
  35494. else {
  35495. defines.LIGHTMAP = false;
  35496. }
  35497. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35498. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35499. return false;
  35500. }
  35501. else {
  35502. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35503. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35504. }
  35505. }
  35506. else {
  35507. defines.SPECULAR = false;
  35508. }
  35509. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35510. // Bump texure can not be not blocking.
  35511. if (!this._bumpTexture.isReady()) {
  35512. return false;
  35513. }
  35514. else {
  35515. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35516. defines.PARALLAX = this._useParallax;
  35517. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35518. }
  35519. }
  35520. else {
  35521. defines.BUMP = false;
  35522. }
  35523. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35524. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35525. return false;
  35526. }
  35527. else {
  35528. defines._needUVs = true;
  35529. defines.REFRACTION = true;
  35530. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35531. }
  35532. }
  35533. else {
  35534. defines.REFRACTION = false;
  35535. }
  35536. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35537. }
  35538. else {
  35539. defines.DIFFUSE = false;
  35540. defines.AMBIENT = false;
  35541. defines.OPACITY = false;
  35542. defines.REFLECTION = false;
  35543. defines.EMISSIVE = false;
  35544. defines.LIGHTMAP = false;
  35545. defines.BUMP = false;
  35546. defines.REFRACTION = false;
  35547. }
  35548. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35549. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35550. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35551. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35552. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35553. }
  35554. if (defines._areImageProcessingDirty) {
  35555. if (!this._imageProcessingConfiguration.isReady()) {
  35556. return false;
  35557. }
  35558. this._imageProcessingConfiguration.prepareDefines(defines);
  35559. }
  35560. if (defines._areFresnelDirty) {
  35561. if (StandardMaterial.FresnelEnabled) {
  35562. // Fresnel
  35563. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35564. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35565. this._reflectionFresnelParameters) {
  35566. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35567. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35568. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35569. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35570. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35571. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35572. defines._needNormals = true;
  35573. defines.FRESNEL = true;
  35574. }
  35575. }
  35576. else {
  35577. defines.FRESNEL = false;
  35578. }
  35579. }
  35580. // Misc.
  35581. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35582. // Attribs
  35583. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35584. // Values that need to be evaluated on every frame
  35585. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35586. // Get correct effect
  35587. if (defines.isDirty) {
  35588. defines.markAsProcessed();
  35589. scene.resetCachedMaterial();
  35590. // Fallbacks
  35591. var fallbacks = new BABYLON.EffectFallbacks();
  35592. if (defines.REFLECTION) {
  35593. fallbacks.addFallback(0, "REFLECTION");
  35594. }
  35595. if (defines.SPECULAR) {
  35596. fallbacks.addFallback(0, "SPECULAR");
  35597. }
  35598. if (defines.BUMP) {
  35599. fallbacks.addFallback(0, "BUMP");
  35600. }
  35601. if (defines.PARALLAX) {
  35602. fallbacks.addFallback(1, "PARALLAX");
  35603. }
  35604. if (defines.PARALLAXOCCLUSION) {
  35605. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35606. }
  35607. if (defines.SPECULAROVERALPHA) {
  35608. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35609. }
  35610. if (defines.FOG) {
  35611. fallbacks.addFallback(1, "FOG");
  35612. }
  35613. if (defines.POINTSIZE) {
  35614. fallbacks.addFallback(0, "POINTSIZE");
  35615. }
  35616. if (defines.LOGARITHMICDEPTH) {
  35617. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35618. }
  35619. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35620. if (defines.SPECULARTERM) {
  35621. fallbacks.addFallback(0, "SPECULARTERM");
  35622. }
  35623. if (defines.DIFFUSEFRESNEL) {
  35624. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35625. }
  35626. if (defines.OPACITYFRESNEL) {
  35627. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35628. }
  35629. if (defines.REFLECTIONFRESNEL) {
  35630. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35631. }
  35632. if (defines.EMISSIVEFRESNEL) {
  35633. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35634. }
  35635. if (defines.FRESNEL) {
  35636. fallbacks.addFallback(4, "FRESNEL");
  35637. }
  35638. //Attributes
  35639. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35640. if (defines.NORMAL) {
  35641. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35642. }
  35643. if (defines.UV1) {
  35644. attribs.push(BABYLON.VertexBuffer.UVKind);
  35645. }
  35646. if (defines.UV2) {
  35647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35648. }
  35649. if (defines.VERTEXCOLOR) {
  35650. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35651. }
  35652. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35653. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35654. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35655. var shaderName = "default";
  35656. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35657. "vFogInfos", "vFogColor", "pointSize",
  35658. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35659. "mBones",
  35660. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35661. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35662. "logarithmicDepthConstant", "vTangentSpaceParams"
  35663. ];
  35664. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35665. var uniformBuffers = ["Material", "Scene"];
  35666. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35667. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35668. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35669. uniformsNames: uniforms,
  35670. uniformBuffersNames: uniformBuffers,
  35671. samplers: samplers,
  35672. defines: defines,
  35673. maxSimultaneousLights: this._maxSimultaneousLights
  35674. });
  35675. if (this.customShaderNameResolve) {
  35676. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35677. }
  35678. var join = defines.toString();
  35679. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35680. attributes: attribs,
  35681. uniformsNames: uniforms,
  35682. uniformBuffersNames: uniformBuffers,
  35683. samplers: samplers,
  35684. defines: join,
  35685. fallbacks: fallbacks,
  35686. onCompiled: this.onCompiled,
  35687. onError: this.onError,
  35688. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35689. }, engine), defines);
  35690. this.buildUniformLayout();
  35691. }
  35692. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35693. return false;
  35694. }
  35695. defines._renderId = scene.getRenderId();
  35696. this._wasPreviouslyReady = true;
  35697. return true;
  35698. };
  35699. StandardMaterial.prototype.buildUniformLayout = function () {
  35700. // Order is important !
  35701. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35702. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35703. this._uniformBuffer.addUniform("opacityParts", 4);
  35704. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35705. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35706. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35707. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35708. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35709. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35710. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35711. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35712. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35713. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35714. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35715. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35716. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35717. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35718. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35719. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35720. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35721. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35722. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35723. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35724. this._uniformBuffer.addUniform("specularMatrix", 16);
  35725. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35726. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35727. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35728. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35729. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35730. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35731. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35732. this._uniformBuffer.addUniform("pointSize", 1);
  35733. this._uniformBuffer.create();
  35734. };
  35735. StandardMaterial.prototype.unbind = function () {
  35736. if (this._activeEffect) {
  35737. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35738. this._activeEffect.setTexture("reflection2DSampler", null);
  35739. }
  35740. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35741. this._activeEffect.setTexture("refraction2DSampler", null);
  35742. }
  35743. }
  35744. _super.prototype.unbind.call(this);
  35745. };
  35746. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35747. var scene = this.getScene();
  35748. var defines = subMesh._materialDefines;
  35749. if (!defines) {
  35750. return;
  35751. }
  35752. var effect = subMesh.effect;
  35753. if (!effect) {
  35754. return;
  35755. }
  35756. this._activeEffect = effect;
  35757. // Matrices
  35758. this.bindOnlyWorldMatrix(world);
  35759. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35760. // Bones
  35761. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35762. if (mustRebind) {
  35763. this._uniformBuffer.bindToEffect(effect, "Material");
  35764. this.bindViewProjection(effect);
  35765. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35766. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35767. // Fresnel
  35768. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35769. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35770. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35771. }
  35772. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35773. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35774. }
  35775. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35776. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35777. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35778. }
  35779. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35780. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35781. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35782. }
  35783. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35784. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35785. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35786. }
  35787. }
  35788. // Textures
  35789. if (scene.texturesEnabled) {
  35790. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35791. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35792. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35793. }
  35794. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35795. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35796. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35797. }
  35798. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35799. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35800. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35801. }
  35802. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35803. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35804. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35805. }
  35806. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35807. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35808. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35809. }
  35810. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35811. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35812. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35813. }
  35814. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35815. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35816. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35817. }
  35818. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35819. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35820. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35821. if (scene._mirroredCameraPosition) {
  35822. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35823. }
  35824. else {
  35825. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35826. }
  35827. }
  35828. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35829. var depth = 1.0;
  35830. if (!this._refractionTexture.isCube) {
  35831. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35832. if (this._refractionTexture.depth) {
  35833. depth = this._refractionTexture.depth;
  35834. }
  35835. }
  35836. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35837. }
  35838. }
  35839. // Point size
  35840. if (this.pointsCloud) {
  35841. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35842. }
  35843. if (defines.SPECULARTERM) {
  35844. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35845. }
  35846. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35847. // Diffuse
  35848. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35849. }
  35850. // Textures
  35851. if (scene.texturesEnabled) {
  35852. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35853. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35854. }
  35855. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35856. effect.setTexture("ambientSampler", this._ambientTexture);
  35857. }
  35858. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35859. effect.setTexture("opacitySampler", this._opacityTexture);
  35860. }
  35861. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35862. if (this._reflectionTexture.isCube) {
  35863. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35864. }
  35865. else {
  35866. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35867. }
  35868. }
  35869. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35870. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35871. }
  35872. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35873. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35874. }
  35875. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35876. effect.setTexture("specularSampler", this._specularTexture);
  35877. }
  35878. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35879. effect.setTexture("bumpSampler", this._bumpTexture);
  35880. }
  35881. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35882. var depth = 1.0;
  35883. if (this._refractionTexture.isCube) {
  35884. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35885. }
  35886. else {
  35887. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35888. }
  35889. }
  35890. }
  35891. // Clip plane
  35892. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35893. // Colors
  35894. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35895. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35896. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35897. }
  35898. if (mustRebind || !this.isFrozen) {
  35899. // Lights
  35900. if (scene.lightsEnabled && !this._disableLighting) {
  35901. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35902. }
  35903. // View
  35904. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35905. this.bindView(effect);
  35906. }
  35907. // Fog
  35908. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35909. // Morph targets
  35910. if (defines.NUM_MORPH_INFLUENCERS) {
  35911. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35912. }
  35913. // Log. depth
  35914. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35915. // image processing
  35916. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35917. this._imageProcessingConfiguration.bind(this._activeEffect);
  35918. }
  35919. }
  35920. this._uniformBuffer.update();
  35921. this._afterBind(mesh, this._activeEffect);
  35922. };
  35923. StandardMaterial.prototype.getAnimatables = function () {
  35924. var results = [];
  35925. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35926. results.push(this._diffuseTexture);
  35927. }
  35928. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35929. results.push(this._ambientTexture);
  35930. }
  35931. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35932. results.push(this._opacityTexture);
  35933. }
  35934. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35935. results.push(this._reflectionTexture);
  35936. }
  35937. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35938. results.push(this._emissiveTexture);
  35939. }
  35940. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35941. results.push(this._specularTexture);
  35942. }
  35943. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35944. results.push(this._bumpTexture);
  35945. }
  35946. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35947. results.push(this._lightmapTexture);
  35948. }
  35949. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35950. results.push(this._refractionTexture);
  35951. }
  35952. return results;
  35953. };
  35954. StandardMaterial.prototype.getActiveTextures = function () {
  35955. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35956. if (this._diffuseTexture) {
  35957. activeTextures.push(this._diffuseTexture);
  35958. }
  35959. if (this._ambientTexture) {
  35960. activeTextures.push(this._ambientTexture);
  35961. }
  35962. if (this._opacityTexture) {
  35963. activeTextures.push(this._opacityTexture);
  35964. }
  35965. if (this._reflectionTexture) {
  35966. activeTextures.push(this._reflectionTexture);
  35967. }
  35968. if (this._emissiveTexture) {
  35969. activeTextures.push(this._emissiveTexture);
  35970. }
  35971. if (this._specularTexture) {
  35972. activeTextures.push(this._specularTexture);
  35973. }
  35974. if (this._bumpTexture) {
  35975. activeTextures.push(this._bumpTexture);
  35976. }
  35977. if (this._lightmapTexture) {
  35978. activeTextures.push(this._lightmapTexture);
  35979. }
  35980. if (this._refractionTexture) {
  35981. activeTextures.push(this._refractionTexture);
  35982. }
  35983. return activeTextures;
  35984. };
  35985. StandardMaterial.prototype.hasTexture = function (texture) {
  35986. if (_super.prototype.hasTexture.call(this, texture)) {
  35987. return true;
  35988. }
  35989. if (this._diffuseTexture === texture) {
  35990. return true;
  35991. }
  35992. if (this._ambientTexture === texture) {
  35993. return true;
  35994. }
  35995. if (this._opacityTexture === texture) {
  35996. return true;
  35997. }
  35998. if (this._reflectionTexture === texture) {
  35999. return true;
  36000. }
  36001. if (this._emissiveTexture === texture) {
  36002. return true;
  36003. }
  36004. if (this._specularTexture === texture) {
  36005. return true;
  36006. }
  36007. if (this._bumpTexture === texture) {
  36008. return true;
  36009. }
  36010. if (this._lightmapTexture === texture) {
  36011. return true;
  36012. }
  36013. if (this._refractionTexture === texture) {
  36014. return true;
  36015. }
  36016. return false;
  36017. };
  36018. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36019. if (forceDisposeTextures) {
  36020. if (this._diffuseTexture) {
  36021. this._diffuseTexture.dispose();
  36022. }
  36023. if (this._ambientTexture) {
  36024. this._ambientTexture.dispose();
  36025. }
  36026. if (this._opacityTexture) {
  36027. this._opacityTexture.dispose();
  36028. }
  36029. if (this._reflectionTexture) {
  36030. this._reflectionTexture.dispose();
  36031. }
  36032. if (this._emissiveTexture) {
  36033. this._emissiveTexture.dispose();
  36034. }
  36035. if (this._specularTexture) {
  36036. this._specularTexture.dispose();
  36037. }
  36038. if (this._bumpTexture) {
  36039. this._bumpTexture.dispose();
  36040. }
  36041. if (this._lightmapTexture) {
  36042. this._lightmapTexture.dispose();
  36043. }
  36044. if (this._refractionTexture) {
  36045. this._refractionTexture.dispose();
  36046. }
  36047. }
  36048. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36049. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36050. }
  36051. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36052. };
  36053. StandardMaterial.prototype.clone = function (name) {
  36054. var _this = this;
  36055. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36056. result.name = name;
  36057. result.id = name;
  36058. return result;
  36059. };
  36060. StandardMaterial.prototype.serialize = function () {
  36061. return BABYLON.SerializationHelper.Serialize(this);
  36062. };
  36063. // Statics
  36064. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36065. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36066. };
  36067. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36068. get: function () {
  36069. return StandardMaterial._DiffuseTextureEnabled;
  36070. },
  36071. set: function (value) {
  36072. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36073. return;
  36074. }
  36075. StandardMaterial._DiffuseTextureEnabled = value;
  36076. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36077. },
  36078. enumerable: true,
  36079. configurable: true
  36080. });
  36081. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36082. get: function () {
  36083. return StandardMaterial._AmbientTextureEnabled;
  36084. },
  36085. set: function (value) {
  36086. if (StandardMaterial._AmbientTextureEnabled === value) {
  36087. return;
  36088. }
  36089. StandardMaterial._AmbientTextureEnabled = value;
  36090. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36091. },
  36092. enumerable: true,
  36093. configurable: true
  36094. });
  36095. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36096. get: function () {
  36097. return StandardMaterial._OpacityTextureEnabled;
  36098. },
  36099. set: function (value) {
  36100. if (StandardMaterial._OpacityTextureEnabled === value) {
  36101. return;
  36102. }
  36103. StandardMaterial._OpacityTextureEnabled = value;
  36104. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36105. },
  36106. enumerable: true,
  36107. configurable: true
  36108. });
  36109. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36110. get: function () {
  36111. return StandardMaterial._ReflectionTextureEnabled;
  36112. },
  36113. set: function (value) {
  36114. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36115. return;
  36116. }
  36117. StandardMaterial._ReflectionTextureEnabled = value;
  36118. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36119. },
  36120. enumerable: true,
  36121. configurable: true
  36122. });
  36123. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36124. get: function () {
  36125. return StandardMaterial._EmissiveTextureEnabled;
  36126. },
  36127. set: function (value) {
  36128. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36129. return;
  36130. }
  36131. StandardMaterial._EmissiveTextureEnabled = value;
  36132. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36133. },
  36134. enumerable: true,
  36135. configurable: true
  36136. });
  36137. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36138. get: function () {
  36139. return StandardMaterial._SpecularTextureEnabled;
  36140. },
  36141. set: function (value) {
  36142. if (StandardMaterial._SpecularTextureEnabled === value) {
  36143. return;
  36144. }
  36145. StandardMaterial._SpecularTextureEnabled = value;
  36146. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36152. get: function () {
  36153. return StandardMaterial._BumpTextureEnabled;
  36154. },
  36155. set: function (value) {
  36156. if (StandardMaterial._BumpTextureEnabled === value) {
  36157. return;
  36158. }
  36159. StandardMaterial._BumpTextureEnabled = value;
  36160. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36161. },
  36162. enumerable: true,
  36163. configurable: true
  36164. });
  36165. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36166. get: function () {
  36167. return StandardMaterial._LightmapTextureEnabled;
  36168. },
  36169. set: function (value) {
  36170. if (StandardMaterial._LightmapTextureEnabled === value) {
  36171. return;
  36172. }
  36173. StandardMaterial._LightmapTextureEnabled = value;
  36174. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36175. },
  36176. enumerable: true,
  36177. configurable: true
  36178. });
  36179. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36180. get: function () {
  36181. return StandardMaterial._RefractionTextureEnabled;
  36182. },
  36183. set: function (value) {
  36184. if (StandardMaterial._RefractionTextureEnabled === value) {
  36185. return;
  36186. }
  36187. StandardMaterial._RefractionTextureEnabled = value;
  36188. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36189. },
  36190. enumerable: true,
  36191. configurable: true
  36192. });
  36193. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36194. get: function () {
  36195. return StandardMaterial._ColorGradingTextureEnabled;
  36196. },
  36197. set: function (value) {
  36198. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36199. return;
  36200. }
  36201. StandardMaterial._ColorGradingTextureEnabled = value;
  36202. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36203. },
  36204. enumerable: true,
  36205. configurable: true
  36206. });
  36207. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36208. get: function () {
  36209. return StandardMaterial._FresnelEnabled;
  36210. },
  36211. set: function (value) {
  36212. if (StandardMaterial._FresnelEnabled === value) {
  36213. return;
  36214. }
  36215. StandardMaterial._FresnelEnabled = value;
  36216. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36217. },
  36218. enumerable: true,
  36219. configurable: true
  36220. });
  36221. // Flags used to enable or disable a type of texture for all Standard Materials
  36222. StandardMaterial._DiffuseTextureEnabled = true;
  36223. StandardMaterial._AmbientTextureEnabled = true;
  36224. StandardMaterial._OpacityTextureEnabled = true;
  36225. StandardMaterial._ReflectionTextureEnabled = true;
  36226. StandardMaterial._EmissiveTextureEnabled = true;
  36227. StandardMaterial._SpecularTextureEnabled = true;
  36228. StandardMaterial._BumpTextureEnabled = true;
  36229. StandardMaterial._LightmapTextureEnabled = true;
  36230. StandardMaterial._RefractionTextureEnabled = true;
  36231. StandardMaterial._ColorGradingTextureEnabled = true;
  36232. StandardMaterial._FresnelEnabled = true;
  36233. __decorate([
  36234. BABYLON.serializeAsTexture("diffuseTexture")
  36235. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36236. __decorate([
  36237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36238. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36239. __decorate([
  36240. BABYLON.serializeAsTexture("ambientTexture")
  36241. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36242. __decorate([
  36243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36244. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36245. __decorate([
  36246. BABYLON.serializeAsTexture("opacityTexture")
  36247. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36248. __decorate([
  36249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36250. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36251. __decorate([
  36252. BABYLON.serializeAsTexture("reflectionTexture")
  36253. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36254. __decorate([
  36255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36256. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36257. __decorate([
  36258. BABYLON.serializeAsTexture("emissiveTexture")
  36259. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36260. __decorate([
  36261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36262. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36263. __decorate([
  36264. BABYLON.serializeAsTexture("specularTexture")
  36265. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36266. __decorate([
  36267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36268. ], StandardMaterial.prototype, "specularTexture", void 0);
  36269. __decorate([
  36270. BABYLON.serializeAsTexture("bumpTexture")
  36271. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36272. __decorate([
  36273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36274. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36275. __decorate([
  36276. BABYLON.serializeAsTexture("lightmapTexture")
  36277. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36278. __decorate([
  36279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36280. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36281. __decorate([
  36282. BABYLON.serializeAsTexture("refractionTexture")
  36283. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36284. __decorate([
  36285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36286. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36287. __decorate([
  36288. BABYLON.serializeAsColor3("ambient")
  36289. ], StandardMaterial.prototype, "ambientColor", void 0);
  36290. __decorate([
  36291. BABYLON.serializeAsColor3("diffuse")
  36292. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36293. __decorate([
  36294. BABYLON.serializeAsColor3("specular")
  36295. ], StandardMaterial.prototype, "specularColor", void 0);
  36296. __decorate([
  36297. BABYLON.serializeAsColor3("emissive")
  36298. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36299. __decorate([
  36300. BABYLON.serialize()
  36301. ], StandardMaterial.prototype, "specularPower", void 0);
  36302. __decorate([
  36303. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36304. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36305. __decorate([
  36306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36307. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36308. __decorate([
  36309. BABYLON.serialize("useEmissiveAsIllumination")
  36310. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36311. __decorate([
  36312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36313. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36314. __decorate([
  36315. BABYLON.serialize("linkEmissiveWithDiffuse")
  36316. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36317. __decorate([
  36318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36319. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36320. __decorate([
  36321. BABYLON.serialize("useSpecularOverAlpha")
  36322. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36323. __decorate([
  36324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36325. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36326. __decorate([
  36327. BABYLON.serialize("useReflectionOverAlpha")
  36328. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36329. __decorate([
  36330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36331. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36332. __decorate([
  36333. BABYLON.serialize("disableLighting")
  36334. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36335. __decorate([
  36336. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36337. ], StandardMaterial.prototype, "disableLighting", void 0);
  36338. __decorate([
  36339. BABYLON.serialize("useParallax")
  36340. ], StandardMaterial.prototype, "_useParallax", void 0);
  36341. __decorate([
  36342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36343. ], StandardMaterial.prototype, "useParallax", void 0);
  36344. __decorate([
  36345. BABYLON.serialize("useParallaxOcclusion")
  36346. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36347. __decorate([
  36348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36349. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36350. __decorate([
  36351. BABYLON.serialize()
  36352. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36353. __decorate([
  36354. BABYLON.serialize("roughness")
  36355. ], StandardMaterial.prototype, "_roughness", void 0);
  36356. __decorate([
  36357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36358. ], StandardMaterial.prototype, "roughness", void 0);
  36359. __decorate([
  36360. BABYLON.serialize()
  36361. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36362. __decorate([
  36363. BABYLON.serialize()
  36364. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36365. __decorate([
  36366. BABYLON.serialize("useLightmapAsShadowmap")
  36367. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36368. __decorate([
  36369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36370. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36371. __decorate([
  36372. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36373. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36374. __decorate([
  36375. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36376. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36377. __decorate([
  36378. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36379. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36380. __decorate([
  36381. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36382. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36383. __decorate([
  36384. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36385. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36386. __decorate([
  36387. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36388. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36389. __decorate([
  36390. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36391. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36392. __decorate([
  36393. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36394. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36395. __decorate([
  36396. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36397. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36398. __decorate([
  36399. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36400. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36401. __decorate([
  36402. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36403. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36404. __decorate([
  36405. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36406. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36407. __decorate([
  36408. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36409. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36410. __decorate([
  36411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36412. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36413. __decorate([
  36414. BABYLON.serialize("maxSimultaneousLights")
  36415. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36416. __decorate([
  36417. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36418. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36419. __decorate([
  36420. BABYLON.serialize("invertNormalMapX")
  36421. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36422. __decorate([
  36423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36424. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36425. __decorate([
  36426. BABYLON.serialize("invertNormalMapY")
  36427. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36428. __decorate([
  36429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36430. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36431. __decorate([
  36432. BABYLON.serialize("twoSidedLighting")
  36433. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36434. __decorate([
  36435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36436. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36437. __decorate([
  36438. BABYLON.serialize()
  36439. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36440. return StandardMaterial;
  36441. }(BABYLON.PushMaterial));
  36442. BABYLON.StandardMaterial = StandardMaterial;
  36443. })(BABYLON || (BABYLON = {}));
  36444. //# sourceMappingURL=babylon.standardMaterial.js.map
  36445. var BABYLON;
  36446. (function (BABYLON) {
  36447. var PBRMaterialDefines = /** @class */ (function (_super) {
  36448. __extends(PBRMaterialDefines, _super);
  36449. function PBRMaterialDefines() {
  36450. var _this = _super.call(this) || this;
  36451. _this.PBR = true;
  36452. _this.MAINUV1 = false;
  36453. _this.MAINUV2 = false;
  36454. _this.UV1 = false;
  36455. _this.UV2 = false;
  36456. _this.ALBEDO = false;
  36457. _this.ALBEDODIRECTUV = 0;
  36458. _this.VERTEXCOLOR = false;
  36459. _this.AMBIENT = false;
  36460. _this.AMBIENTDIRECTUV = 0;
  36461. _this.AMBIENTINGRAYSCALE = false;
  36462. _this.OPACITY = false;
  36463. _this.VERTEXALPHA = false;
  36464. _this.OPACITYDIRECTUV = 0;
  36465. _this.OPACITYRGB = false;
  36466. _this.ALPHATEST = false;
  36467. _this.DEPTHPREPASS = false;
  36468. _this.ALPHABLEND = false;
  36469. _this.ALPHAFROMALBEDO = false;
  36470. _this.ALPHATESTVALUE = 0.5;
  36471. _this.SPECULAROVERALPHA = false;
  36472. _this.RADIANCEOVERALPHA = false;
  36473. _this.ALPHAFRESNEL = false;
  36474. _this.LINEARALPHAFRESNEL = false;
  36475. _this.PREMULTIPLYALPHA = false;
  36476. _this.EMISSIVE = false;
  36477. _this.EMISSIVEDIRECTUV = 0;
  36478. _this.REFLECTIVITY = false;
  36479. _this.REFLECTIVITYDIRECTUV = 0;
  36480. _this.SPECULARTERM = false;
  36481. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36482. _this.MICROSURFACEAUTOMATIC = false;
  36483. _this.LODBASEDMICROSFURACE = false;
  36484. _this.MICROSURFACEMAP = false;
  36485. _this.MICROSURFACEMAPDIRECTUV = 0;
  36486. _this.METALLICWORKFLOW = false;
  36487. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36488. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36489. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36490. _this.AOSTOREINMETALMAPRED = false;
  36491. _this.ENVIRONMENTBRDF = false;
  36492. _this.NORMAL = false;
  36493. _this.TANGENT = false;
  36494. _this.BUMP = false;
  36495. _this.BUMPDIRECTUV = 0;
  36496. _this.PARALLAX = false;
  36497. _this.PARALLAXOCCLUSION = false;
  36498. _this.NORMALXYSCALE = true;
  36499. _this.LIGHTMAP = false;
  36500. _this.LIGHTMAPDIRECTUV = 0;
  36501. _this.USELIGHTMAPASSHADOWMAP = false;
  36502. _this.REFLECTION = false;
  36503. _this.REFLECTIONMAP_3D = false;
  36504. _this.REFLECTIONMAP_SPHERICAL = false;
  36505. _this.REFLECTIONMAP_PLANAR = false;
  36506. _this.REFLECTIONMAP_CUBIC = false;
  36507. _this.REFLECTIONMAP_PROJECTION = false;
  36508. _this.REFLECTIONMAP_SKYBOX = false;
  36509. _this.REFLECTIONMAP_EXPLICIT = false;
  36510. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36511. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36512. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36513. _this.INVERTCUBICMAP = false;
  36514. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36515. _this.USESPHERICALINVERTEX = false;
  36516. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36517. _this.LODINREFLECTIONALPHA = false;
  36518. _this.GAMMAREFLECTION = false;
  36519. _this.RADIANCEOCCLUSION = false;
  36520. _this.HORIZONOCCLUSION = false;
  36521. _this.REFRACTION = false;
  36522. _this.REFRACTIONMAP_3D = false;
  36523. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36524. _this.LODINREFRACTIONALPHA = false;
  36525. _this.GAMMAREFRACTION = false;
  36526. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36527. _this.INSTANCES = false;
  36528. _this.NUM_BONE_INFLUENCERS = 0;
  36529. _this.BonesPerMesh = 0;
  36530. _this.NONUNIFORMSCALING = false;
  36531. _this.MORPHTARGETS = false;
  36532. _this.MORPHTARGETS_NORMAL = false;
  36533. _this.MORPHTARGETS_TANGENT = false;
  36534. _this.NUM_MORPH_INFLUENCERS = 0;
  36535. _this.IMAGEPROCESSING = false;
  36536. _this.VIGNETTE = false;
  36537. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36538. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36539. _this.TONEMAPPING = false;
  36540. _this.CONTRAST = false;
  36541. _this.COLORCURVES = false;
  36542. _this.COLORGRADING = false;
  36543. _this.COLORGRADING3D = false;
  36544. _this.SAMPLER3DGREENDEPTH = false;
  36545. _this.SAMPLER3DBGRMAP = false;
  36546. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36547. _this.EXPOSURE = false;
  36548. _this.USEPHYSICALLIGHTFALLOFF = false;
  36549. _this.TWOSIDEDLIGHTING = false;
  36550. _this.SHADOWFLOAT = false;
  36551. _this.CLIPPLANE = false;
  36552. _this.POINTSIZE = false;
  36553. _this.FOG = false;
  36554. _this.LOGARITHMICDEPTH = false;
  36555. _this.FORCENORMALFORWARD = false;
  36556. _this.rebuild();
  36557. return _this;
  36558. }
  36559. PBRMaterialDefines.prototype.reset = function () {
  36560. _super.prototype.reset.call(this);
  36561. this.ALPHATESTVALUE = 0.5;
  36562. this.PBR = true;
  36563. };
  36564. return PBRMaterialDefines;
  36565. }(BABYLON.MaterialDefines));
  36566. /**
  36567. * The Physically based material base class of BJS.
  36568. *
  36569. * This offers the main features of a standard PBR material.
  36570. * For more information, please refer to the documentation :
  36571. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36572. */
  36573. var PBRBaseMaterial = /** @class */ (function (_super) {
  36574. __extends(PBRBaseMaterial, _super);
  36575. /**
  36576. * Instantiates a new PBRMaterial instance.
  36577. *
  36578. * @param name The material name
  36579. * @param scene The scene the material will be use in.
  36580. */
  36581. function PBRBaseMaterial(name, scene) {
  36582. var _this = _super.call(this, name, scene) || this;
  36583. /**
  36584. * Intensity of the direct lights e.g. the four lights available in your scene.
  36585. * This impacts both the direct diffuse and specular highlights.
  36586. */
  36587. _this._directIntensity = 1.0;
  36588. /**
  36589. * Intensity of the emissive part of the material.
  36590. * This helps controlling the emissive effect without modifying the emissive color.
  36591. */
  36592. _this._emissiveIntensity = 1.0;
  36593. /**
  36594. * Intensity of the environment e.g. how much the environment will light the object
  36595. * either through harmonics for rough material or through the refelction for shiny ones.
  36596. */
  36597. _this._environmentIntensity = 1.0;
  36598. /**
  36599. * This is a special control allowing the reduction of the specular highlights coming from the
  36600. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36601. */
  36602. _this._specularIntensity = 1.0;
  36603. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36604. /**
  36605. * Debug Control allowing disabling the bump map on this material.
  36606. */
  36607. _this._disableBumpMap = false;
  36608. /**
  36609. * AKA Occlusion Texture Intensity in other nomenclature.
  36610. */
  36611. _this._ambientTextureStrength = 1.0;
  36612. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36613. /**
  36614. * AKA Diffuse Color in other nomenclature.
  36615. */
  36616. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36617. /**
  36618. * AKA Specular Color in other nomenclature.
  36619. */
  36620. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36621. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36622. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36623. /**
  36624. * AKA Glossiness in other nomenclature.
  36625. */
  36626. _this._microSurface = 0.9;
  36627. /**
  36628. * source material index of refraction (IOR)' / 'destination material IOR.
  36629. */
  36630. _this._indexOfRefraction = 0.66;
  36631. /**
  36632. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36633. */
  36634. _this._invertRefractionY = false;
  36635. /**
  36636. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36637. * Materials half opaque for instance using refraction could benefit from this control.
  36638. */
  36639. _this._linkRefractionWithTransparency = false;
  36640. _this._useLightmapAsShadowmap = false;
  36641. /**
  36642. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36643. * makes the reflect vector face the model (under horizon).
  36644. */
  36645. _this._useHorizonOcclusion = true;
  36646. /**
  36647. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36648. * too much the area relying on ambient texture to define their ambient occlusion.
  36649. */
  36650. _this._useRadianceOcclusion = true;
  36651. /**
  36652. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36653. */
  36654. _this._useAlphaFromAlbedoTexture = false;
  36655. /**
  36656. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36657. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36658. */
  36659. _this._useSpecularOverAlpha = true;
  36660. /**
  36661. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36662. */
  36663. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36664. /**
  36665. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36666. */
  36667. _this._useRoughnessFromMetallicTextureAlpha = true;
  36668. /**
  36669. * Specifies if the metallic texture contains the roughness information in its green channel.
  36670. */
  36671. _this._useRoughnessFromMetallicTextureGreen = false;
  36672. /**
  36673. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36674. */
  36675. _this._useMetallnessFromMetallicTextureBlue = false;
  36676. /**
  36677. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36678. */
  36679. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36680. /**
  36681. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36682. */
  36683. _this._useAmbientInGrayScale = false;
  36684. /**
  36685. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36686. * The material will try to infer what glossiness each pixel should be.
  36687. */
  36688. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36689. /**
  36690. * BJS is using an harcoded light falloff based on a manually sets up range.
  36691. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36692. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36693. */
  36694. _this._usePhysicalLightFalloff = true;
  36695. /**
  36696. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36697. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36698. */
  36699. _this._useRadianceOverAlpha = true;
  36700. /**
  36701. * Allows using the bump map in parallax mode.
  36702. */
  36703. _this._useParallax = false;
  36704. /**
  36705. * Allows using the bump map in parallax occlusion mode.
  36706. */
  36707. _this._useParallaxOcclusion = false;
  36708. /**
  36709. * Controls the scale bias of the parallax mode.
  36710. */
  36711. _this._parallaxScaleBias = 0.05;
  36712. /**
  36713. * If sets to true, disables all the lights affecting the material.
  36714. */
  36715. _this._disableLighting = false;
  36716. /**
  36717. * Number of Simultaneous lights allowed on the material.
  36718. */
  36719. _this._maxSimultaneousLights = 4;
  36720. /**
  36721. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36722. */
  36723. _this._invertNormalMapX = false;
  36724. /**
  36725. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36726. */
  36727. _this._invertNormalMapY = false;
  36728. /**
  36729. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36730. */
  36731. _this._twoSidedLighting = false;
  36732. /**
  36733. * Defines the alpha limits in alpha test mode.
  36734. */
  36735. _this._alphaCutOff = 0.4;
  36736. /**
  36737. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36738. */
  36739. _this._forceAlphaTest = false;
  36740. /**
  36741. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36742. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36743. */
  36744. _this._useAlphaFresnel = false;
  36745. /**
  36746. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36747. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36748. */
  36749. _this._useLinearAlphaFresnel = false;
  36750. /**
  36751. * The transparency mode of the material.
  36752. */
  36753. _this._transparencyMode = null;
  36754. /**
  36755. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36756. * from cos thetav and roughness:
  36757. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36758. */
  36759. _this._environmentBRDFTexture = null;
  36760. /**
  36761. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36762. */
  36763. _this._forceIrradianceInFragment = false;
  36764. /**
  36765. * Force normal to face away from face.
  36766. */
  36767. _this._forceNormalForward = false;
  36768. /**
  36769. * Force metallic workflow.
  36770. */
  36771. _this._forceMetallicWorkflow = false;
  36772. _this._renderTargets = new BABYLON.SmartArray(16);
  36773. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36774. // Setup the default processing configuration to the scene.
  36775. _this._attachImageProcessingConfiguration(null);
  36776. _this.getRenderTargetTextures = function () {
  36777. _this._renderTargets.reset();
  36778. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36779. _this._renderTargets.push(_this._reflectionTexture);
  36780. }
  36781. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36782. _this._renderTargets.push(_this._refractionTexture);
  36783. }
  36784. return _this._renderTargets;
  36785. };
  36786. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36787. return _this;
  36788. }
  36789. /**
  36790. * Attaches a new image processing configuration to the PBR Material.
  36791. * @param configuration
  36792. */
  36793. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36794. var _this = this;
  36795. if (configuration === this._imageProcessingConfiguration) {
  36796. return;
  36797. }
  36798. // Detaches observer.
  36799. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36800. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36801. }
  36802. // Pick the scene configuration if needed.
  36803. if (!configuration) {
  36804. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36805. }
  36806. else {
  36807. this._imageProcessingConfiguration = configuration;
  36808. }
  36809. // Attaches observer.
  36810. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36811. _this._markAllSubMeshesAsImageProcessingDirty();
  36812. });
  36813. };
  36814. PBRBaseMaterial.prototype.getClassName = function () {
  36815. return "PBRBaseMaterial";
  36816. };
  36817. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36818. get: function () {
  36819. return this._useLogarithmicDepth;
  36820. },
  36821. set: function (value) {
  36822. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36823. },
  36824. enumerable: true,
  36825. configurable: true
  36826. });
  36827. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36828. /**
  36829. * Gets the current transparency mode.
  36830. */
  36831. get: function () {
  36832. return this._transparencyMode;
  36833. },
  36834. /**
  36835. * Sets the transparency mode of the material.
  36836. */
  36837. set: function (value) {
  36838. if (this._transparencyMode === value) {
  36839. return;
  36840. }
  36841. this._transparencyMode = value;
  36842. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36843. this._markAllSubMeshesAsTexturesDirty();
  36844. },
  36845. enumerable: true,
  36846. configurable: true
  36847. });
  36848. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36849. /**
  36850. * Returns true if alpha blending should be disabled.
  36851. */
  36852. get: function () {
  36853. return (this._linkRefractionWithTransparency ||
  36854. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36855. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36856. },
  36857. enumerable: true,
  36858. configurable: true
  36859. });
  36860. /**
  36861. * Specifies whether or not this material should be rendered in alpha blend mode.
  36862. */
  36863. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36864. if (this._disableAlphaBlending) {
  36865. return false;
  36866. }
  36867. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36868. };
  36869. /**
  36870. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36871. */
  36872. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36873. if (this._disableAlphaBlending) {
  36874. return false;
  36875. }
  36876. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36877. };
  36878. /**
  36879. * Specifies whether or not this material should be rendered in alpha test mode.
  36880. */
  36881. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36882. if (this._forceAlphaTest) {
  36883. return true;
  36884. }
  36885. if (this._linkRefractionWithTransparency) {
  36886. return false;
  36887. }
  36888. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36889. };
  36890. /**
  36891. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36892. */
  36893. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36894. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36895. };
  36896. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36897. return this._albedoTexture;
  36898. };
  36899. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36900. var _this = this;
  36901. if (subMesh.effect && this.isFrozen) {
  36902. if (this._wasPreviouslyReady) {
  36903. return true;
  36904. }
  36905. }
  36906. if (!subMesh._materialDefines) {
  36907. subMesh._materialDefines = new PBRMaterialDefines();
  36908. }
  36909. var scene = this.getScene();
  36910. var defines = subMesh._materialDefines;
  36911. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36912. if (defines._renderId === scene.getRenderId()) {
  36913. return true;
  36914. }
  36915. }
  36916. var engine = scene.getEngine();
  36917. // Lights
  36918. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36919. defines._needNormals = true;
  36920. // Textures
  36921. if (defines._areTexturesDirty) {
  36922. defines._needUVs = false;
  36923. if (scene.texturesEnabled) {
  36924. if (scene.getEngine().getCaps().textureLOD) {
  36925. defines.LODBASEDMICROSFURACE = true;
  36926. }
  36927. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36928. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36929. return false;
  36930. }
  36931. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36932. }
  36933. else {
  36934. defines.ALBEDO = false;
  36935. }
  36936. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36937. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36938. return false;
  36939. }
  36940. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36941. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36942. }
  36943. else {
  36944. defines.AMBIENT = false;
  36945. }
  36946. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36947. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36948. return false;
  36949. }
  36950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36951. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36952. }
  36953. else {
  36954. defines.OPACITY = false;
  36955. }
  36956. var reflectionTexture = this._getReflectionTexture();
  36957. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36958. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36959. return false;
  36960. }
  36961. defines.REFLECTION = true;
  36962. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36963. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36964. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36965. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36966. defines.INVERTCUBICMAP = true;
  36967. }
  36968. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36969. switch (reflectionTexture.coordinatesMode) {
  36970. case BABYLON.Texture.CUBIC_MODE:
  36971. case BABYLON.Texture.INVCUBIC_MODE:
  36972. defines.REFLECTIONMAP_CUBIC = true;
  36973. break;
  36974. case BABYLON.Texture.EXPLICIT_MODE:
  36975. defines.REFLECTIONMAP_EXPLICIT = true;
  36976. break;
  36977. case BABYLON.Texture.PLANAR_MODE:
  36978. defines.REFLECTIONMAP_PLANAR = true;
  36979. break;
  36980. case BABYLON.Texture.PROJECTION_MODE:
  36981. defines.REFLECTIONMAP_PROJECTION = true;
  36982. break;
  36983. case BABYLON.Texture.SKYBOX_MODE:
  36984. defines.REFLECTIONMAP_SKYBOX = true;
  36985. break;
  36986. case BABYLON.Texture.SPHERICAL_MODE:
  36987. defines.REFLECTIONMAP_SPHERICAL = true;
  36988. break;
  36989. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36990. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36991. break;
  36992. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36993. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36994. break;
  36995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36996. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36997. break;
  36998. }
  36999. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37000. if (reflectionTexture.sphericalPolynomial) {
  37001. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37002. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37003. defines.USESPHERICALINVERTEX = false;
  37004. }
  37005. else {
  37006. defines.USESPHERICALINVERTEX = true;
  37007. }
  37008. }
  37009. }
  37010. }
  37011. else {
  37012. defines.REFLECTION = false;
  37013. defines.REFLECTIONMAP_3D = false;
  37014. defines.REFLECTIONMAP_SPHERICAL = false;
  37015. defines.REFLECTIONMAP_PLANAR = false;
  37016. defines.REFLECTIONMAP_CUBIC = false;
  37017. defines.REFLECTIONMAP_PROJECTION = false;
  37018. defines.REFLECTIONMAP_SKYBOX = false;
  37019. defines.REFLECTIONMAP_EXPLICIT = false;
  37020. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37021. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37022. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37023. defines.INVERTCUBICMAP = false;
  37024. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37025. defines.USESPHERICALINVERTEX = false;
  37026. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37027. defines.LODINREFLECTIONALPHA = false;
  37028. defines.GAMMAREFLECTION = false;
  37029. }
  37030. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37031. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37032. return false;
  37033. }
  37034. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37035. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37036. }
  37037. else {
  37038. defines.LIGHTMAP = false;
  37039. }
  37040. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37041. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37042. return false;
  37043. }
  37044. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37045. }
  37046. else {
  37047. defines.EMISSIVE = false;
  37048. }
  37049. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37050. if (this._metallicTexture) {
  37051. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37052. return false;
  37053. }
  37054. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37055. defines.METALLICWORKFLOW = true;
  37056. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37057. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37058. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37059. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37060. }
  37061. else if (this._reflectivityTexture) {
  37062. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37063. return false;
  37064. }
  37065. defines.METALLICWORKFLOW = false;
  37066. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37067. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37068. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37069. }
  37070. else {
  37071. defines.METALLICWORKFLOW = false;
  37072. defines.REFLECTIVITY = false;
  37073. }
  37074. if (this._microSurfaceTexture) {
  37075. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37076. return false;
  37077. }
  37078. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37079. }
  37080. else {
  37081. defines.MICROSURFACEMAP = false;
  37082. }
  37083. }
  37084. else {
  37085. defines.REFLECTIVITY = false;
  37086. defines.MICROSURFACEMAP = false;
  37087. }
  37088. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37089. // Bump texure can not be none blocking.
  37090. if (!this._bumpTexture.isReady()) {
  37091. return false;
  37092. }
  37093. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37094. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37095. defines.PARALLAX = true;
  37096. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37097. }
  37098. else {
  37099. defines.PARALLAX = false;
  37100. }
  37101. }
  37102. else {
  37103. defines.BUMP = false;
  37104. }
  37105. var refractionTexture = this._getRefractionTexture();
  37106. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37107. if (!refractionTexture.isReadyOrNotBlocking()) {
  37108. return false;
  37109. }
  37110. defines.REFRACTION = true;
  37111. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37112. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37113. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37114. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37115. if (this._linkRefractionWithTransparency) {
  37116. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37117. }
  37118. }
  37119. else {
  37120. defines.REFRACTION = false;
  37121. }
  37122. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37123. // This is blocking.
  37124. if (!this._environmentBRDFTexture.isReady()) {
  37125. return false;
  37126. }
  37127. defines.ENVIRONMENTBRDF = true;
  37128. }
  37129. else {
  37130. defines.ENVIRONMENTBRDF = false;
  37131. }
  37132. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37133. defines.ALPHAFROMALBEDO = true;
  37134. }
  37135. else {
  37136. defines.ALPHAFROMALBEDO = false;
  37137. }
  37138. }
  37139. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37140. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37141. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37142. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37143. defines.METALLICWORKFLOW = true;
  37144. }
  37145. else {
  37146. defines.METALLICWORKFLOW = false;
  37147. }
  37148. if (!this.backFaceCulling && this._twoSidedLighting) {
  37149. defines.TWOSIDEDLIGHTING = true;
  37150. }
  37151. else {
  37152. defines.TWOSIDEDLIGHTING = false;
  37153. }
  37154. defines.ALPHATESTVALUE = this._alphaCutOff;
  37155. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37156. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37157. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37158. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37159. }
  37160. if (defines._areImageProcessingDirty) {
  37161. if (!this._imageProcessingConfiguration.isReady()) {
  37162. return false;
  37163. }
  37164. this._imageProcessingConfiguration.prepareDefines(defines);
  37165. }
  37166. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37167. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37168. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37169. // Misc.
  37170. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37171. // Values that need to be evaluated on every frame
  37172. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  37173. // Attribs
  37174. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37175. var bufferMesh = null;
  37176. if (mesh instanceof BABYLON.InstancedMesh) {
  37177. bufferMesh = mesh.sourceMesh;
  37178. }
  37179. else if (mesh instanceof BABYLON.Mesh) {
  37180. bufferMesh = mesh;
  37181. }
  37182. if (bufferMesh) {
  37183. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37184. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37185. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37186. var normals = normalVertexBuffer.getData();
  37187. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37188. var strideSize = normalVertexBuffer.getStrideSize();
  37189. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37190. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37191. defines.NORMAL = false;
  37192. }
  37193. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37194. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37195. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37196. var tangents = tangentVertexBuffer.getData();
  37197. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37198. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37199. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37200. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37201. defines.TANGENT = false;
  37202. }
  37203. }
  37204. }
  37205. else {
  37206. if (!scene.getEngine().getCaps().standardDerivatives) {
  37207. bufferMesh.createNormals(true);
  37208. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37209. }
  37210. }
  37211. }
  37212. }
  37213. // Get correct effect
  37214. if (defines.isDirty) {
  37215. defines.markAsProcessed();
  37216. scene.resetCachedMaterial();
  37217. // Fallbacks
  37218. var fallbacks = new BABYLON.EffectFallbacks();
  37219. var fallbackRank = 0;
  37220. if (defines.USESPHERICALINVERTEX) {
  37221. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37222. }
  37223. if (defines.FOG) {
  37224. fallbacks.addFallback(fallbackRank, "FOG");
  37225. }
  37226. if (defines.POINTSIZE) {
  37227. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37228. }
  37229. if (defines.LOGARITHMICDEPTH) {
  37230. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37231. }
  37232. if (defines.PARALLAX) {
  37233. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37234. }
  37235. if (defines.PARALLAXOCCLUSION) {
  37236. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37237. }
  37238. if (defines.ENVIRONMENTBRDF) {
  37239. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37240. }
  37241. if (defines.TANGENT) {
  37242. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37243. }
  37244. if (defines.BUMP) {
  37245. fallbacks.addFallback(fallbackRank++, "BUMP");
  37246. }
  37247. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37248. if (defines.SPECULARTERM) {
  37249. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37250. }
  37251. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37252. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37253. }
  37254. if (defines.LIGHTMAP) {
  37255. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37256. }
  37257. if (defines.NORMAL) {
  37258. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37259. }
  37260. if (defines.AMBIENT) {
  37261. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37262. }
  37263. if (defines.EMISSIVE) {
  37264. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37265. }
  37266. if (defines.VERTEXCOLOR) {
  37267. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37268. }
  37269. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37270. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37271. }
  37272. if (defines.MORPHTARGETS) {
  37273. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37274. }
  37275. //Attributes
  37276. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37277. if (defines.NORMAL) {
  37278. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37279. }
  37280. if (defines.TANGENT) {
  37281. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37282. }
  37283. if (defines.UV1) {
  37284. attribs.push(BABYLON.VertexBuffer.UVKind);
  37285. }
  37286. if (defines.UV2) {
  37287. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37288. }
  37289. if (defines.VERTEXCOLOR) {
  37290. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37291. }
  37292. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37293. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37294. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37295. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37296. "vFogInfos", "vFogColor", "pointSize",
  37297. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37298. "mBones",
  37299. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37300. "vLightingIntensity",
  37301. "logarithmicDepthConstant",
  37302. "vSphericalX", "vSphericalY", "vSphericalZ",
  37303. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37304. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37305. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37306. "vTangentSpaceParams"
  37307. ];
  37308. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37309. "bumpSampler", "lightmapSampler", "opacitySampler",
  37310. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37311. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37312. "microSurfaceSampler", "environmentBrdfSampler"];
  37313. var uniformBuffers = ["Material", "Scene"];
  37314. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37315. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37316. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37317. uniformsNames: uniforms,
  37318. uniformBuffersNames: uniformBuffers,
  37319. samplers: samplers,
  37320. defines: defines,
  37321. maxSimultaneousLights: this._maxSimultaneousLights
  37322. });
  37323. var onCompiled = function (effect) {
  37324. if (_this.onCompiled) {
  37325. _this.onCompiled(effect);
  37326. }
  37327. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37328. };
  37329. var join = defines.toString();
  37330. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37331. attributes: attribs,
  37332. uniformsNames: uniforms,
  37333. uniformBuffersNames: uniformBuffers,
  37334. samplers: samplers,
  37335. defines: join,
  37336. fallbacks: fallbacks,
  37337. onCompiled: onCompiled,
  37338. onError: this.onError,
  37339. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37340. }, engine), defines);
  37341. this.buildUniformLayout();
  37342. }
  37343. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37344. return false;
  37345. }
  37346. defines._renderId = scene.getRenderId();
  37347. this._wasPreviouslyReady = true;
  37348. return true;
  37349. };
  37350. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37351. // Order is important !
  37352. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37353. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37354. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37355. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37356. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37357. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37358. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37359. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37360. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37361. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37362. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37363. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37364. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37365. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37366. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37367. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37368. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37369. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37370. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37371. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37372. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37373. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37374. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37375. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37376. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37377. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37378. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37379. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37380. this._uniformBuffer.addUniform("pointSize", 1);
  37381. this._uniformBuffer.create();
  37382. };
  37383. PBRBaseMaterial.prototype.unbind = function () {
  37384. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37385. this._uniformBuffer.setTexture("reflectionSampler", null);
  37386. }
  37387. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37388. this._uniformBuffer.setTexture("refractionSampler", null);
  37389. }
  37390. _super.prototype.unbind.call(this);
  37391. };
  37392. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37393. this._activeEffect.setMatrix("world", world);
  37394. };
  37395. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37396. var scene = this.getScene();
  37397. var defines = subMesh._materialDefines;
  37398. if (!defines) {
  37399. return;
  37400. }
  37401. var effect = subMesh.effect;
  37402. if (!effect) {
  37403. return;
  37404. }
  37405. this._activeEffect = effect;
  37406. // Matrices
  37407. this.bindOnlyWorldMatrix(world);
  37408. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37409. // Bones
  37410. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37411. var reflectionTexture = null;
  37412. if (mustRebind) {
  37413. this._uniformBuffer.bindToEffect(effect, "Material");
  37414. this.bindViewProjection(effect);
  37415. reflectionTexture = this._getReflectionTexture();
  37416. var refractionTexture = this._getRefractionTexture();
  37417. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37418. // Texture uniforms
  37419. if (scene.texturesEnabled) {
  37420. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37421. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37422. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37423. }
  37424. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37425. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37426. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37427. }
  37428. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37429. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37430. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37431. }
  37432. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37433. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37434. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37435. var polynomials = reflectionTexture.sphericalPolynomial;
  37436. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37437. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37438. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37439. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37440. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37441. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37442. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37443. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37444. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37445. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37446. }
  37447. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37448. }
  37449. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37450. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37451. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37452. }
  37453. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37454. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37455. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37456. }
  37457. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37458. if (this._metallicTexture) {
  37459. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37460. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37461. }
  37462. else if (this._reflectivityTexture) {
  37463. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37464. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37465. }
  37466. if (this._microSurfaceTexture) {
  37467. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37468. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37469. }
  37470. }
  37471. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37472. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37473. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37474. if (scene._mirroredCameraPosition) {
  37475. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37476. }
  37477. else {
  37478. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37479. }
  37480. }
  37481. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37482. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37483. var depth = 1.0;
  37484. if (!refractionTexture.isCube) {
  37485. if (refractionTexture.depth) {
  37486. depth = refractionTexture.depth;
  37487. }
  37488. }
  37489. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37490. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37491. }
  37492. }
  37493. // Point size
  37494. if (this.pointsCloud) {
  37495. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37496. }
  37497. // Colors
  37498. if (defines.METALLICWORKFLOW) {
  37499. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37500. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37501. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37502. }
  37503. else {
  37504. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37505. }
  37506. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37507. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37508. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37509. // Misc
  37510. this._lightingInfos.x = this._directIntensity;
  37511. this._lightingInfos.y = this._emissiveIntensity;
  37512. this._lightingInfos.z = this._environmentIntensity;
  37513. this._lightingInfos.w = this._specularIntensity;
  37514. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37515. }
  37516. // Textures
  37517. if (scene.texturesEnabled) {
  37518. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37519. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37520. }
  37521. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37522. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37523. }
  37524. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37525. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37526. }
  37527. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37528. if (defines.LODBASEDMICROSFURACE) {
  37529. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37530. }
  37531. else {
  37532. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37533. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37534. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37535. }
  37536. }
  37537. if (defines.ENVIRONMENTBRDF) {
  37538. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37539. }
  37540. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37541. if (defines.LODBASEDMICROSFURACE) {
  37542. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37543. }
  37544. else {
  37545. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37546. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37547. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37548. }
  37549. }
  37550. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37551. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37552. }
  37553. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37554. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37555. }
  37556. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37557. if (this._metallicTexture) {
  37558. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37559. }
  37560. else if (this._reflectivityTexture) {
  37561. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37562. }
  37563. if (this._microSurfaceTexture) {
  37564. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37565. }
  37566. }
  37567. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37568. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37569. }
  37570. }
  37571. // Clip plane
  37572. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37573. // Colors
  37574. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37575. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37576. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37577. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37578. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37579. }
  37580. if (mustRebind || !this.isFrozen) {
  37581. // Lights
  37582. if (scene.lightsEnabled && !this._disableLighting) {
  37583. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37584. }
  37585. // View
  37586. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37587. this.bindView(effect);
  37588. }
  37589. // Fog
  37590. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37591. // Morph targets
  37592. if (defines.NUM_MORPH_INFLUENCERS) {
  37593. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37594. }
  37595. // image processing
  37596. this._imageProcessingConfiguration.bind(this._activeEffect);
  37597. // Log. depth
  37598. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37599. }
  37600. this._uniformBuffer.update();
  37601. this._afterBind(mesh);
  37602. };
  37603. PBRBaseMaterial.prototype.getAnimatables = function () {
  37604. var results = [];
  37605. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37606. results.push(this._albedoTexture);
  37607. }
  37608. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37609. results.push(this._ambientTexture);
  37610. }
  37611. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37612. results.push(this._opacityTexture);
  37613. }
  37614. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37615. results.push(this._reflectionTexture);
  37616. }
  37617. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37618. results.push(this._emissiveTexture);
  37619. }
  37620. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37621. results.push(this._metallicTexture);
  37622. }
  37623. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37624. results.push(this._reflectivityTexture);
  37625. }
  37626. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37627. results.push(this._bumpTexture);
  37628. }
  37629. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37630. results.push(this._lightmapTexture);
  37631. }
  37632. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37633. results.push(this._refractionTexture);
  37634. }
  37635. return results;
  37636. };
  37637. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37638. if (this._reflectionTexture) {
  37639. return this._reflectionTexture;
  37640. }
  37641. return this.getScene().environmentTexture;
  37642. };
  37643. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37644. if (this._refractionTexture) {
  37645. return this._refractionTexture;
  37646. }
  37647. if (this._linkRefractionWithTransparency) {
  37648. return this.getScene().environmentTexture;
  37649. }
  37650. return null;
  37651. };
  37652. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37653. if (forceDisposeTextures) {
  37654. if (this._albedoTexture) {
  37655. this._albedoTexture.dispose();
  37656. }
  37657. if (this._ambientTexture) {
  37658. this._ambientTexture.dispose();
  37659. }
  37660. if (this._opacityTexture) {
  37661. this._opacityTexture.dispose();
  37662. }
  37663. if (this._reflectionTexture) {
  37664. this._reflectionTexture.dispose();
  37665. }
  37666. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37667. this._environmentBRDFTexture.dispose();
  37668. }
  37669. if (this._emissiveTexture) {
  37670. this._emissiveTexture.dispose();
  37671. }
  37672. if (this._metallicTexture) {
  37673. this._metallicTexture.dispose();
  37674. }
  37675. if (this._reflectivityTexture) {
  37676. this._reflectivityTexture.dispose();
  37677. }
  37678. if (this._bumpTexture) {
  37679. this._bumpTexture.dispose();
  37680. }
  37681. if (this._lightmapTexture) {
  37682. this._lightmapTexture.dispose();
  37683. }
  37684. if (this._refractionTexture) {
  37685. this._refractionTexture.dispose();
  37686. }
  37687. }
  37688. this._renderTargets.dispose();
  37689. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37690. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37691. }
  37692. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37693. };
  37694. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37695. __decorate([
  37696. BABYLON.serializeAsImageProcessingConfiguration()
  37697. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37698. __decorate([
  37699. BABYLON.serialize()
  37700. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37701. __decorate([
  37702. BABYLON.serialize()
  37703. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37704. return PBRBaseMaterial;
  37705. }(BABYLON.PushMaterial));
  37706. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37707. })(BABYLON || (BABYLON = {}));
  37708. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37709. var BABYLON;
  37710. (function (BABYLON) {
  37711. /**
  37712. * The Physically based simple base material of BJS.
  37713. *
  37714. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37715. * It is used as the base class for both the specGloss and metalRough conventions.
  37716. */
  37717. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37718. __extends(PBRBaseSimpleMaterial, _super);
  37719. /**
  37720. * Instantiates a new PBRMaterial instance.
  37721. *
  37722. * @param name The material name
  37723. * @param scene The scene the material will be use in.
  37724. */
  37725. function PBRBaseSimpleMaterial(name, scene) {
  37726. var _this = _super.call(this, name, scene) || this;
  37727. /**
  37728. * Number of Simultaneous lights allowed on the material.
  37729. */
  37730. _this.maxSimultaneousLights = 4;
  37731. /**
  37732. * If sets to true, disables all the lights affecting the material.
  37733. */
  37734. _this.disableLighting = false;
  37735. /**
  37736. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37737. */
  37738. _this.invertNormalMapX = false;
  37739. /**
  37740. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37741. */
  37742. _this.invertNormalMapY = false;
  37743. /**
  37744. * Emissivie color used to self-illuminate the model.
  37745. */
  37746. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37747. /**
  37748. * Occlusion Channel Strenght.
  37749. */
  37750. _this.occlusionStrength = 1.0;
  37751. _this.useLightmapAsShadowmap = false;
  37752. _this._useAlphaFromAlbedoTexture = true;
  37753. _this._useAmbientInGrayScale = true;
  37754. return _this;
  37755. }
  37756. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37757. /**
  37758. * Gets the current double sided mode.
  37759. */
  37760. get: function () {
  37761. return this._twoSidedLighting;
  37762. },
  37763. /**
  37764. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37765. */
  37766. set: function (value) {
  37767. if (this._twoSidedLighting === value) {
  37768. return;
  37769. }
  37770. this._twoSidedLighting = value;
  37771. this.backFaceCulling = !value;
  37772. this._markAllSubMeshesAsTexturesDirty();
  37773. },
  37774. enumerable: true,
  37775. configurable: true
  37776. });
  37777. /**
  37778. * Return the active textures of the material.
  37779. */
  37780. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37781. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37782. if (this.environmentTexture) {
  37783. activeTextures.push(this.environmentTexture);
  37784. }
  37785. if (this.normalTexture) {
  37786. activeTextures.push(this.normalTexture);
  37787. }
  37788. if (this.emissiveTexture) {
  37789. activeTextures.push(this.emissiveTexture);
  37790. }
  37791. if (this.occlusionTexture) {
  37792. activeTextures.push(this.occlusionTexture);
  37793. }
  37794. if (this.lightmapTexture) {
  37795. activeTextures.push(this.lightmapTexture);
  37796. }
  37797. return activeTextures;
  37798. };
  37799. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37800. if (_super.prototype.hasTexture.call(this, texture)) {
  37801. return true;
  37802. }
  37803. if (this.lightmapTexture === texture) {
  37804. return true;
  37805. }
  37806. return false;
  37807. };
  37808. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37809. return "PBRBaseSimpleMaterial";
  37810. };
  37811. __decorate([
  37812. BABYLON.serialize(),
  37813. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37814. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37815. __decorate([
  37816. BABYLON.serialize(),
  37817. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37818. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37819. __decorate([
  37820. BABYLON.serializeAsTexture(),
  37821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37822. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37823. __decorate([
  37824. BABYLON.serialize(),
  37825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37826. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37827. __decorate([
  37828. BABYLON.serialize(),
  37829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37830. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37831. __decorate([
  37832. BABYLON.serializeAsTexture(),
  37833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37834. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37835. __decorate([
  37836. BABYLON.serializeAsColor3("emissive"),
  37837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37838. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37839. __decorate([
  37840. BABYLON.serializeAsTexture(),
  37841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37842. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37843. __decorate([
  37844. BABYLON.serialize(),
  37845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37846. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37847. __decorate([
  37848. BABYLON.serializeAsTexture(),
  37849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37850. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37851. __decorate([
  37852. BABYLON.serialize(),
  37853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37854. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37855. __decorate([
  37856. BABYLON.serialize()
  37857. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37858. __decorate([
  37859. BABYLON.serializeAsTexture(),
  37860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37861. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37862. __decorate([
  37863. BABYLON.serialize(),
  37864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37865. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37866. return PBRBaseSimpleMaterial;
  37867. }(BABYLON.PBRBaseMaterial));
  37868. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37869. })(BABYLON || (BABYLON = {}));
  37870. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37871. var BABYLON;
  37872. (function (BABYLON) {
  37873. /**
  37874. * The Physically based material of BJS.
  37875. *
  37876. * This offers the main features of a standard PBR material.
  37877. * For more information, please refer to the documentation :
  37878. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37879. */
  37880. var PBRMaterial = /** @class */ (function (_super) {
  37881. __extends(PBRMaterial, _super);
  37882. /**
  37883. * Instantiates a new PBRMaterial instance.
  37884. *
  37885. * @param name The material name
  37886. * @param scene The scene the material will be use in.
  37887. */
  37888. function PBRMaterial(name, scene) {
  37889. var _this = _super.call(this, name, scene) || this;
  37890. /**
  37891. * Intensity of the direct lights e.g. the four lights available in your scene.
  37892. * This impacts both the direct diffuse and specular highlights.
  37893. */
  37894. _this.directIntensity = 1.0;
  37895. /**
  37896. * Intensity of the emissive part of the material.
  37897. * This helps controlling the emissive effect without modifying the emissive color.
  37898. */
  37899. _this.emissiveIntensity = 1.0;
  37900. /**
  37901. * Intensity of the environment e.g. how much the environment will light the object
  37902. * either through harmonics for rough material or through the refelction for shiny ones.
  37903. */
  37904. _this.environmentIntensity = 1.0;
  37905. /**
  37906. * This is a special control allowing the reduction of the specular highlights coming from the
  37907. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37908. */
  37909. _this.specularIntensity = 1.0;
  37910. /**
  37911. * Debug Control allowing disabling the bump map on this material.
  37912. */
  37913. _this.disableBumpMap = false;
  37914. /**
  37915. * AKA Occlusion Texture Intensity in other nomenclature.
  37916. */
  37917. _this.ambientTextureStrength = 1.0;
  37918. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37919. /**
  37920. * AKA Diffuse Color in other nomenclature.
  37921. */
  37922. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37923. /**
  37924. * AKA Specular Color in other nomenclature.
  37925. */
  37926. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37927. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37928. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37929. /**
  37930. * AKA Glossiness in other nomenclature.
  37931. */
  37932. _this.microSurface = 1.0;
  37933. /**
  37934. * source material index of refraction (IOR)' / 'destination material IOR.
  37935. */
  37936. _this.indexOfRefraction = 0.66;
  37937. /**
  37938. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37939. */
  37940. _this.invertRefractionY = false;
  37941. /**
  37942. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37943. * Materials half opaque for instance using refraction could benefit from this control.
  37944. */
  37945. _this.linkRefractionWithTransparency = false;
  37946. _this.useLightmapAsShadowmap = false;
  37947. /**
  37948. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37949. */
  37950. _this.useAlphaFromAlbedoTexture = false;
  37951. /**
  37952. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37953. */
  37954. _this.forceAlphaTest = false;
  37955. /**
  37956. * Defines the alpha limits in alpha test mode.
  37957. */
  37958. _this.alphaCutOff = 0.4;
  37959. /**
  37960. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37961. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37962. */
  37963. _this.useSpecularOverAlpha = true;
  37964. /**
  37965. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37966. */
  37967. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37968. /**
  37969. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37970. */
  37971. _this.useRoughnessFromMetallicTextureAlpha = true;
  37972. /**
  37973. * Specifies if the metallic texture contains the roughness information in its green channel.
  37974. */
  37975. _this.useRoughnessFromMetallicTextureGreen = false;
  37976. /**
  37977. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37978. */
  37979. _this.useMetallnessFromMetallicTextureBlue = false;
  37980. /**
  37981. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37982. */
  37983. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37984. /**
  37985. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37986. */
  37987. _this.useAmbientInGrayScale = false;
  37988. /**
  37989. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37990. * The material will try to infer what glossiness each pixel should be.
  37991. */
  37992. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37993. /**
  37994. * BJS is using an harcoded light falloff based on a manually sets up range.
  37995. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37996. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37997. */
  37998. _this.usePhysicalLightFalloff = true;
  37999. /**
  38000. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38001. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38002. */
  38003. _this.useRadianceOverAlpha = true;
  38004. /**
  38005. * Allows using the bump map in parallax mode.
  38006. */
  38007. _this.useParallax = false;
  38008. /**
  38009. * Allows using the bump map in parallax occlusion mode.
  38010. */
  38011. _this.useParallaxOcclusion = false;
  38012. /**
  38013. * Controls the scale bias of the parallax mode.
  38014. */
  38015. _this.parallaxScaleBias = 0.05;
  38016. /**
  38017. * If sets to true, disables all the lights affecting the material.
  38018. */
  38019. _this.disableLighting = false;
  38020. /**
  38021. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38022. */
  38023. _this.forceIrradianceInFragment = false;
  38024. /**
  38025. * Number of Simultaneous lights allowed on the material.
  38026. */
  38027. _this.maxSimultaneousLights = 4;
  38028. /**
  38029. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38030. */
  38031. _this.invertNormalMapX = false;
  38032. /**
  38033. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38034. */
  38035. _this.invertNormalMapY = false;
  38036. /**
  38037. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38038. */
  38039. _this.twoSidedLighting = false;
  38040. /**
  38041. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38042. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38043. */
  38044. _this.useAlphaFresnel = false;
  38045. /**
  38046. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38047. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38048. */
  38049. _this.useLinearAlphaFresnel = false;
  38050. /**
  38051. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38052. * And/Or occlude the blended part.
  38053. */
  38054. _this.environmentBRDFTexture = null;
  38055. /**
  38056. * Force normal to face away from face.
  38057. */
  38058. _this.forceNormalForward = false;
  38059. /**
  38060. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38061. * makes the reflect vector face the model (under horizon).
  38062. */
  38063. _this.useHorizonOcclusion = true;
  38064. /**
  38065. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38066. * too much the area relying on ambient texture to define their ambient occlusion.
  38067. */
  38068. _this.useRadianceOcclusion = true;
  38069. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38070. return _this;
  38071. }
  38072. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38073. /**
  38074. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38075. */
  38076. get: function () {
  38077. return this._PBRMATERIAL_OPAQUE;
  38078. },
  38079. enumerable: true,
  38080. configurable: true
  38081. });
  38082. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38083. /**
  38084. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38085. */
  38086. get: function () {
  38087. return this._PBRMATERIAL_ALPHATEST;
  38088. },
  38089. enumerable: true,
  38090. configurable: true
  38091. });
  38092. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38093. /**
  38094. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38095. */
  38096. get: function () {
  38097. return this._PBRMATERIAL_ALPHABLEND;
  38098. },
  38099. enumerable: true,
  38100. configurable: true
  38101. });
  38102. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38103. /**
  38104. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38105. * They are also discarded below the alpha cutoff threshold to improve performances.
  38106. */
  38107. get: function () {
  38108. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38109. },
  38110. enumerable: true,
  38111. configurable: true
  38112. });
  38113. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38114. /**
  38115. * Gets the image processing configuration used either in this material.
  38116. */
  38117. get: function () {
  38118. return this._imageProcessingConfiguration;
  38119. },
  38120. /**
  38121. * Sets the Default image processing configuration used either in the this material.
  38122. *
  38123. * If sets to null, the scene one is in use.
  38124. */
  38125. set: function (value) {
  38126. this._attachImageProcessingConfiguration(value);
  38127. // Ensure the effect will be rebuilt.
  38128. this._markAllSubMeshesAsTexturesDirty();
  38129. },
  38130. enumerable: true,
  38131. configurable: true
  38132. });
  38133. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38134. /**
  38135. * Gets wether the color curves effect is enabled.
  38136. */
  38137. get: function () {
  38138. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38139. },
  38140. /**
  38141. * Sets wether the color curves effect is enabled.
  38142. */
  38143. set: function (value) {
  38144. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38145. },
  38146. enumerable: true,
  38147. configurable: true
  38148. });
  38149. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38150. /**
  38151. * Gets wether the color grading effect is enabled.
  38152. */
  38153. get: function () {
  38154. return this.imageProcessingConfiguration.colorGradingEnabled;
  38155. },
  38156. /**
  38157. * Gets wether the color grading effect is enabled.
  38158. */
  38159. set: function (value) {
  38160. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38161. },
  38162. enumerable: true,
  38163. configurable: true
  38164. });
  38165. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38166. /**
  38167. * Gets wether tonemapping is enabled or not.
  38168. */
  38169. get: function () {
  38170. return this._imageProcessingConfiguration.toneMappingEnabled;
  38171. },
  38172. /**
  38173. * Sets wether tonemapping is enabled or not
  38174. */
  38175. set: function (value) {
  38176. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38177. },
  38178. enumerable: true,
  38179. configurable: true
  38180. });
  38181. ;
  38182. ;
  38183. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38184. /**
  38185. * The camera exposure used on this material.
  38186. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38187. * This corresponds to a photographic exposure.
  38188. */
  38189. get: function () {
  38190. return this._imageProcessingConfiguration.exposure;
  38191. },
  38192. /**
  38193. * The camera exposure used on this material.
  38194. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38195. * This corresponds to a photographic exposure.
  38196. */
  38197. set: function (value) {
  38198. this._imageProcessingConfiguration.exposure = value;
  38199. },
  38200. enumerable: true,
  38201. configurable: true
  38202. });
  38203. ;
  38204. ;
  38205. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38206. /**
  38207. * Gets The camera contrast used on this material.
  38208. */
  38209. get: function () {
  38210. return this._imageProcessingConfiguration.contrast;
  38211. },
  38212. /**
  38213. * Sets The camera contrast used on this material.
  38214. */
  38215. set: function (value) {
  38216. this._imageProcessingConfiguration.contrast = value;
  38217. },
  38218. enumerable: true,
  38219. configurable: true
  38220. });
  38221. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38222. /**
  38223. * Gets the Color Grading 2D Lookup Texture.
  38224. */
  38225. get: function () {
  38226. return this._imageProcessingConfiguration.colorGradingTexture;
  38227. },
  38228. /**
  38229. * Sets the Color Grading 2D Lookup Texture.
  38230. */
  38231. set: function (value) {
  38232. this._imageProcessingConfiguration.colorGradingTexture = value;
  38233. },
  38234. enumerable: true,
  38235. configurable: true
  38236. });
  38237. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38238. /**
  38239. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38240. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38241. * 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;
  38242. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38243. */
  38244. get: function () {
  38245. return this._imageProcessingConfiguration.colorCurves;
  38246. },
  38247. /**
  38248. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38249. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38250. * 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;
  38251. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38252. */
  38253. set: function (value) {
  38254. this._imageProcessingConfiguration.colorCurves = value;
  38255. },
  38256. enumerable: true,
  38257. configurable: true
  38258. });
  38259. PBRMaterial.prototype.getClassName = function () {
  38260. return "PBRMaterial";
  38261. };
  38262. PBRMaterial.prototype.getActiveTextures = function () {
  38263. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38264. if (this._albedoTexture) {
  38265. activeTextures.push(this._albedoTexture);
  38266. }
  38267. if (this._ambientTexture) {
  38268. activeTextures.push(this._ambientTexture);
  38269. }
  38270. if (this._opacityTexture) {
  38271. activeTextures.push(this._opacityTexture);
  38272. }
  38273. if (this._reflectionTexture) {
  38274. activeTextures.push(this._reflectionTexture);
  38275. }
  38276. if (this._emissiveTexture) {
  38277. activeTextures.push(this._emissiveTexture);
  38278. }
  38279. if (this._reflectivityTexture) {
  38280. activeTextures.push(this._reflectivityTexture);
  38281. }
  38282. if (this._metallicTexture) {
  38283. activeTextures.push(this._metallicTexture);
  38284. }
  38285. if (this._microSurfaceTexture) {
  38286. activeTextures.push(this._microSurfaceTexture);
  38287. }
  38288. if (this._bumpTexture) {
  38289. activeTextures.push(this._bumpTexture);
  38290. }
  38291. if (this._lightmapTexture) {
  38292. activeTextures.push(this._lightmapTexture);
  38293. }
  38294. if (this._refractionTexture) {
  38295. activeTextures.push(this._refractionTexture);
  38296. }
  38297. return activeTextures;
  38298. };
  38299. PBRMaterial.prototype.hasTexture = function (texture) {
  38300. if (_super.prototype.hasTexture.call(this, texture)) {
  38301. return true;
  38302. }
  38303. if (this._albedoTexture === texture) {
  38304. return true;
  38305. }
  38306. if (this._ambientTexture === texture) {
  38307. return true;
  38308. }
  38309. if (this._opacityTexture === texture) {
  38310. return true;
  38311. }
  38312. if (this._reflectionTexture === texture) {
  38313. return true;
  38314. }
  38315. if (this._reflectivityTexture === texture) {
  38316. return true;
  38317. }
  38318. if (this._metallicTexture === texture) {
  38319. return true;
  38320. }
  38321. if (this._microSurfaceTexture === texture) {
  38322. return true;
  38323. }
  38324. if (this._bumpTexture === texture) {
  38325. return true;
  38326. }
  38327. if (this._lightmapTexture === texture) {
  38328. return true;
  38329. }
  38330. if (this._refractionTexture === texture) {
  38331. return true;
  38332. }
  38333. return false;
  38334. };
  38335. PBRMaterial.prototype.clone = function (name) {
  38336. var _this = this;
  38337. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38338. clone.id = name;
  38339. clone.name = name;
  38340. return clone;
  38341. };
  38342. PBRMaterial.prototype.serialize = function () {
  38343. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38344. serializationObject.customType = "BABYLON.PBRMaterial";
  38345. return serializationObject;
  38346. };
  38347. // Statics
  38348. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38349. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38350. };
  38351. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38352. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38353. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38354. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38355. __decorate([
  38356. BABYLON.serialize(),
  38357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38358. ], PBRMaterial.prototype, "directIntensity", void 0);
  38359. __decorate([
  38360. BABYLON.serialize(),
  38361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38362. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38363. __decorate([
  38364. BABYLON.serialize(),
  38365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38366. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38367. __decorate([
  38368. BABYLON.serialize(),
  38369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38370. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38371. __decorate([
  38372. BABYLON.serialize(),
  38373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38374. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38375. __decorate([
  38376. BABYLON.serializeAsTexture(),
  38377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38378. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38379. __decorate([
  38380. BABYLON.serializeAsTexture(),
  38381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38382. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38383. __decorate([
  38384. BABYLON.serialize(),
  38385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38386. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38387. __decorate([
  38388. BABYLON.serializeAsTexture(),
  38389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38390. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38391. __decorate([
  38392. BABYLON.serializeAsTexture(),
  38393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38394. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38395. __decorate([
  38396. BABYLON.serializeAsTexture(),
  38397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38398. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38399. __decorate([
  38400. BABYLON.serializeAsTexture(),
  38401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38402. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38403. __decorate([
  38404. BABYLON.serializeAsTexture(),
  38405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38406. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38407. __decorate([
  38408. BABYLON.serialize(),
  38409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38410. ], PBRMaterial.prototype, "metallic", void 0);
  38411. __decorate([
  38412. BABYLON.serialize(),
  38413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38414. ], PBRMaterial.prototype, "roughness", void 0);
  38415. __decorate([
  38416. BABYLON.serializeAsTexture(),
  38417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38418. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38419. __decorate([
  38420. BABYLON.serializeAsTexture(),
  38421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38422. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38423. __decorate([
  38424. BABYLON.serializeAsTexture(),
  38425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38426. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38427. __decorate([
  38428. BABYLON.serializeAsTexture(),
  38429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38430. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38431. __decorate([
  38432. BABYLON.serializeAsColor3("ambient"),
  38433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38434. ], PBRMaterial.prototype, "ambientColor", void 0);
  38435. __decorate([
  38436. BABYLON.serializeAsColor3("albedo"),
  38437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38438. ], PBRMaterial.prototype, "albedoColor", void 0);
  38439. __decorate([
  38440. BABYLON.serializeAsColor3("reflectivity"),
  38441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38442. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38443. __decorate([
  38444. BABYLON.serializeAsColor3("reflection"),
  38445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38446. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38447. __decorate([
  38448. BABYLON.serializeAsColor3("emissive"),
  38449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38450. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38451. __decorate([
  38452. BABYLON.serialize(),
  38453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38454. ], PBRMaterial.prototype, "microSurface", void 0);
  38455. __decorate([
  38456. BABYLON.serialize(),
  38457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38458. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38459. __decorate([
  38460. BABYLON.serialize(),
  38461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38462. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38463. __decorate([
  38464. BABYLON.serialize(),
  38465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38466. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38467. __decorate([
  38468. BABYLON.serialize(),
  38469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38470. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38471. __decorate([
  38472. BABYLON.serialize(),
  38473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38474. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38475. __decorate([
  38476. BABYLON.serialize(),
  38477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38478. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38479. __decorate([
  38480. BABYLON.serialize(),
  38481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38482. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38483. __decorate([
  38484. BABYLON.serialize(),
  38485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38486. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38487. __decorate([
  38488. BABYLON.serialize(),
  38489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38490. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38491. __decorate([
  38492. BABYLON.serialize(),
  38493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38494. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38495. __decorate([
  38496. BABYLON.serialize(),
  38497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38498. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38499. __decorate([
  38500. BABYLON.serialize(),
  38501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38502. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38503. __decorate([
  38504. BABYLON.serialize(),
  38505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38506. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38507. __decorate([
  38508. BABYLON.serialize(),
  38509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38510. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38511. __decorate([
  38512. BABYLON.serialize(),
  38513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38514. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38515. __decorate([
  38516. BABYLON.serialize(),
  38517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38518. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38519. __decorate([
  38520. BABYLON.serialize(),
  38521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38522. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38523. __decorate([
  38524. BABYLON.serialize(),
  38525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38526. ], PBRMaterial.prototype, "useParallax", void 0);
  38527. __decorate([
  38528. BABYLON.serialize(),
  38529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38530. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38531. __decorate([
  38532. BABYLON.serialize(),
  38533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38534. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38535. __decorate([
  38536. BABYLON.serialize(),
  38537. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38538. ], PBRMaterial.prototype, "disableLighting", void 0);
  38539. __decorate([
  38540. BABYLON.serialize(),
  38541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38542. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38543. __decorate([
  38544. BABYLON.serialize(),
  38545. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38546. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38547. __decorate([
  38548. BABYLON.serialize(),
  38549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38550. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38551. __decorate([
  38552. BABYLON.serialize(),
  38553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38554. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38555. __decorate([
  38556. BABYLON.serialize(),
  38557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38558. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38559. __decorate([
  38560. BABYLON.serialize(),
  38561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38562. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38563. __decorate([
  38564. BABYLON.serialize(),
  38565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38566. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38567. __decorate([
  38568. BABYLON.serializeAsTexture(),
  38569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38570. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38571. __decorate([
  38572. BABYLON.serialize(),
  38573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38574. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38575. __decorate([
  38576. BABYLON.serialize(),
  38577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38578. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38579. __decorate([
  38580. BABYLON.serialize(),
  38581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38582. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38583. return PBRMaterial;
  38584. }(BABYLON.PBRBaseMaterial));
  38585. BABYLON.PBRMaterial = PBRMaterial;
  38586. })(BABYLON || (BABYLON = {}));
  38587. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38588. var BABYLON;
  38589. (function (BABYLON) {
  38590. /**
  38591. * The PBR material of BJS following the metal roughness convention.
  38592. *
  38593. * This fits to the PBR convention in the GLTF definition:
  38594. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38595. */
  38596. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38597. __extends(PBRMetallicRoughnessMaterial, _super);
  38598. /**
  38599. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38600. *
  38601. * @param name The material name
  38602. * @param scene The scene the material will be use in.
  38603. */
  38604. function PBRMetallicRoughnessMaterial(name, scene) {
  38605. var _this = _super.call(this, name, scene) || this;
  38606. _this._useRoughnessFromMetallicTextureAlpha = false;
  38607. _this._useRoughnessFromMetallicTextureGreen = true;
  38608. _this._useMetallnessFromMetallicTextureBlue = true;
  38609. _this._forceMetallicWorkflow = true;
  38610. return _this;
  38611. }
  38612. /**
  38613. * Return the currrent class name of the material.
  38614. */
  38615. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38616. return "PBRMetallicRoughnessMaterial";
  38617. };
  38618. /**
  38619. * Return the active textures of the material.
  38620. */
  38621. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38622. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38623. if (this.baseTexture) {
  38624. activeTextures.push(this.baseTexture);
  38625. }
  38626. if (this.metallicRoughnessTexture) {
  38627. activeTextures.push(this.metallicRoughnessTexture);
  38628. }
  38629. return activeTextures;
  38630. };
  38631. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38632. if (_super.prototype.hasTexture.call(this, texture)) {
  38633. return true;
  38634. }
  38635. if (this.baseTexture === texture) {
  38636. return true;
  38637. }
  38638. if (this.metallicRoughnessTexture === texture) {
  38639. return true;
  38640. }
  38641. return false;
  38642. };
  38643. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38644. var _this = this;
  38645. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38646. clone.id = name;
  38647. clone.name = name;
  38648. return clone;
  38649. };
  38650. /**
  38651. * Serialize the material to a parsable JSON object.
  38652. */
  38653. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38654. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38655. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38656. return serializationObject;
  38657. };
  38658. /**
  38659. * Parses a JSON object correponding to the serialize function.
  38660. */
  38661. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38662. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38663. };
  38664. __decorate([
  38665. BABYLON.serializeAsColor3(),
  38666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38667. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38668. __decorate([
  38669. BABYLON.serializeAsTexture(),
  38670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38671. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38672. __decorate([
  38673. BABYLON.serialize(),
  38674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38675. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38676. __decorate([
  38677. BABYLON.serialize(),
  38678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38679. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38680. __decorate([
  38681. BABYLON.serializeAsTexture(),
  38682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38683. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38684. return PBRMetallicRoughnessMaterial;
  38685. }(BABYLON.PBRBaseSimpleMaterial));
  38686. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38687. })(BABYLON || (BABYLON = {}));
  38688. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38689. var BABYLON;
  38690. (function (BABYLON) {
  38691. /**
  38692. * The PBR material of BJS following the specular glossiness convention.
  38693. *
  38694. * This fits to the PBR convention in the GLTF definition:
  38695. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38696. */
  38697. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38698. __extends(PBRSpecularGlossinessMaterial, _super);
  38699. /**
  38700. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38701. *
  38702. * @param name The material name
  38703. * @param scene The scene the material will be use in.
  38704. */
  38705. function PBRSpecularGlossinessMaterial(name, scene) {
  38706. var _this = _super.call(this, name, scene) || this;
  38707. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38708. return _this;
  38709. }
  38710. /**
  38711. * Return the currrent class name of the material.
  38712. */
  38713. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38714. return "PBRSpecularGlossinessMaterial";
  38715. };
  38716. /**
  38717. * Return the active textures of the material.
  38718. */
  38719. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38720. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38721. if (this.diffuseTexture) {
  38722. activeTextures.push(this.diffuseTexture);
  38723. }
  38724. if (this.specularGlossinessTexture) {
  38725. activeTextures.push(this.specularGlossinessTexture);
  38726. }
  38727. return activeTextures;
  38728. };
  38729. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38730. if (_super.prototype.hasTexture.call(this, texture)) {
  38731. return true;
  38732. }
  38733. if (this.diffuseTexture === texture) {
  38734. return true;
  38735. }
  38736. if (this.specularGlossinessTexture === texture) {
  38737. return true;
  38738. }
  38739. return false;
  38740. };
  38741. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38742. var _this = this;
  38743. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38744. clone.id = name;
  38745. clone.name = name;
  38746. return clone;
  38747. };
  38748. /**
  38749. * Serialize the material to a parsable JSON object.
  38750. */
  38751. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38753. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38754. return serializationObject;
  38755. };
  38756. /**
  38757. * Parses a JSON object correponding to the serialize function.
  38758. */
  38759. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38760. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38761. };
  38762. __decorate([
  38763. BABYLON.serializeAsColor3("diffuse"),
  38764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38765. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38766. __decorate([
  38767. BABYLON.serializeAsTexture(),
  38768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38769. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38770. __decorate([
  38771. BABYLON.serializeAsColor3("specular"),
  38772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38773. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38774. __decorate([
  38775. BABYLON.serialize(),
  38776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38777. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38778. __decorate([
  38779. BABYLON.serializeAsTexture(),
  38780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38781. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38782. return PBRSpecularGlossinessMaterial;
  38783. }(BABYLON.PBRBaseSimpleMaterial));
  38784. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38785. })(BABYLON || (BABYLON = {}));
  38786. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38787. var BABYLON;
  38788. (function (BABYLON) {
  38789. BABYLON.CameraInputTypes = {};
  38790. var CameraInputsManager = /** @class */ (function () {
  38791. function CameraInputsManager(camera) {
  38792. this.attached = {};
  38793. this.camera = camera;
  38794. this.checkInputs = function () { };
  38795. }
  38796. CameraInputsManager.prototype.add = function (input) {
  38797. var type = input.getSimpleName();
  38798. if (this.attached[type]) {
  38799. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38800. return;
  38801. }
  38802. this.attached[type] = input;
  38803. input.camera = this.camera;
  38804. //for checkInputs, we are dynamically creating a function
  38805. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38806. if (input.checkInputs) {
  38807. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38808. }
  38809. if (this.attachedElement) {
  38810. input.attachControl(this.attachedElement);
  38811. }
  38812. };
  38813. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38814. for (var cam in this.attached) {
  38815. var input = this.attached[cam];
  38816. if (input === inputToRemove) {
  38817. input.detachControl(this.attachedElement);
  38818. input.camera = null;
  38819. delete this.attached[cam];
  38820. this.rebuildInputCheck();
  38821. }
  38822. }
  38823. };
  38824. CameraInputsManager.prototype.removeByType = function (inputType) {
  38825. for (var cam in this.attached) {
  38826. var input = this.attached[cam];
  38827. if (input.getClassName() === inputType) {
  38828. input.detachControl(this.attachedElement);
  38829. input.camera = null;
  38830. delete this.attached[cam];
  38831. this.rebuildInputCheck();
  38832. }
  38833. }
  38834. };
  38835. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38836. var current = this.checkInputs;
  38837. return function () {
  38838. current();
  38839. fn();
  38840. };
  38841. };
  38842. CameraInputsManager.prototype.attachInput = function (input) {
  38843. if (this.attachedElement) {
  38844. input.attachControl(this.attachedElement, this.noPreventDefault);
  38845. }
  38846. };
  38847. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38848. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38849. if (this.attachedElement) {
  38850. return;
  38851. }
  38852. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38853. this.attachedElement = element;
  38854. this.noPreventDefault = noPreventDefault;
  38855. for (var cam in this.attached) {
  38856. this.attached[cam].attachControl(element, noPreventDefault);
  38857. }
  38858. };
  38859. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38860. if (disconnect === void 0) { disconnect = false; }
  38861. if (this.attachedElement !== element) {
  38862. return;
  38863. }
  38864. for (var cam in this.attached) {
  38865. this.attached[cam].detachControl(element);
  38866. if (disconnect) {
  38867. this.attached[cam].camera = null;
  38868. }
  38869. }
  38870. this.attachedElement = null;
  38871. };
  38872. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38873. this.checkInputs = function () { };
  38874. for (var cam in this.attached) {
  38875. var input = this.attached[cam];
  38876. if (input.checkInputs) {
  38877. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38878. }
  38879. }
  38880. };
  38881. CameraInputsManager.prototype.clear = function () {
  38882. if (this.attachedElement) {
  38883. this.detachElement(this.attachedElement, true);
  38884. }
  38885. this.attached = {};
  38886. this.attachedElement = null;
  38887. this.checkInputs = function () { };
  38888. };
  38889. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38890. var inputs = {};
  38891. for (var cam in this.attached) {
  38892. var input = this.attached[cam];
  38893. var res = BABYLON.SerializationHelper.Serialize(input);
  38894. inputs[input.getClassName()] = res;
  38895. }
  38896. serializedCamera.inputsmgr = inputs;
  38897. };
  38898. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38899. var parsedInputs = parsedCamera.inputsmgr;
  38900. if (parsedInputs) {
  38901. this.clear();
  38902. for (var n in parsedInputs) {
  38903. var construct = BABYLON.CameraInputTypes[n];
  38904. if (construct) {
  38905. var parsedinput = parsedInputs[n];
  38906. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38907. this.add(input);
  38908. }
  38909. }
  38910. }
  38911. else {
  38912. //2016-03-08 this part is for managing backward compatibility
  38913. for (var n in this.attached) {
  38914. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38915. if (construct) {
  38916. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38917. this.remove(this.attached[n]);
  38918. this.add(input);
  38919. }
  38920. }
  38921. }
  38922. };
  38923. return CameraInputsManager;
  38924. }());
  38925. BABYLON.CameraInputsManager = CameraInputsManager;
  38926. })(BABYLON || (BABYLON = {}));
  38927. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38928. var BABYLON;
  38929. (function (BABYLON) {
  38930. var TargetCamera = /** @class */ (function (_super) {
  38931. __extends(TargetCamera, _super);
  38932. function TargetCamera(name, position, scene) {
  38933. var _this = _super.call(this, name, position, scene) || this;
  38934. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38935. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38936. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38937. _this.speed = 2.0;
  38938. _this.noRotationConstraint = false;
  38939. _this.lockedTarget = null;
  38940. _this._currentTarget = BABYLON.Vector3.Zero();
  38941. _this._viewMatrix = BABYLON.Matrix.Zero();
  38942. _this._camMatrix = BABYLON.Matrix.Zero();
  38943. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38944. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38945. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38946. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38947. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38948. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38949. _this._tempMatrix = BABYLON.Matrix.Zero();
  38950. return _this;
  38951. }
  38952. TargetCamera.prototype.getFrontPosition = function (distance) {
  38953. this.getWorldMatrix();
  38954. var direction = this.getTarget().subtract(this.position);
  38955. direction.normalize();
  38956. direction.scaleInPlace(distance);
  38957. return this.globalPosition.add(direction);
  38958. };
  38959. TargetCamera.prototype._getLockedTargetPosition = function () {
  38960. if (!this.lockedTarget) {
  38961. return null;
  38962. }
  38963. if (this.lockedTarget.absolutePosition) {
  38964. this.lockedTarget.computeWorldMatrix();
  38965. }
  38966. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38967. };
  38968. TargetCamera.prototype.storeState = function () {
  38969. this._storedPosition = this.position.clone();
  38970. this._storedRotation = this.rotation.clone();
  38971. if (this.rotationQuaternion) {
  38972. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38973. }
  38974. return _super.prototype.storeState.call(this);
  38975. };
  38976. /**
  38977. * Restored camera state. You must call storeState() first
  38978. */
  38979. TargetCamera.prototype._restoreStateValues = function () {
  38980. if (!_super.prototype._restoreStateValues.call(this)) {
  38981. return false;
  38982. }
  38983. this.position = this._storedPosition.clone();
  38984. this.rotation = this._storedRotation.clone();
  38985. if (this.rotationQuaternion) {
  38986. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38987. }
  38988. this.cameraDirection.copyFromFloats(0, 0, 0);
  38989. this.cameraRotation.copyFromFloats(0, 0);
  38990. return true;
  38991. };
  38992. // Cache
  38993. TargetCamera.prototype._initCache = function () {
  38994. _super.prototype._initCache.call(this);
  38995. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38996. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38997. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38998. };
  38999. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39000. if (!ignoreParentClass) {
  39001. _super.prototype._updateCache.call(this);
  39002. }
  39003. var lockedTargetPosition = this._getLockedTargetPosition();
  39004. if (!lockedTargetPosition) {
  39005. this._cache.lockedTarget = null;
  39006. }
  39007. else {
  39008. if (!this._cache.lockedTarget) {
  39009. this._cache.lockedTarget = lockedTargetPosition.clone();
  39010. }
  39011. else {
  39012. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39013. }
  39014. }
  39015. this._cache.rotation.copyFrom(this.rotation);
  39016. if (this.rotationQuaternion)
  39017. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39018. };
  39019. // Synchronized
  39020. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39021. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39022. return false;
  39023. }
  39024. var lockedTargetPosition = this._getLockedTargetPosition();
  39025. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39026. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39027. };
  39028. // Methods
  39029. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39030. var engine = this.getEngine();
  39031. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39032. };
  39033. // Target
  39034. TargetCamera.prototype.setTarget = function (target) {
  39035. this.upVector.normalize();
  39036. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39037. this._camMatrix.invert();
  39038. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39039. var vDir = target.subtract(this.position);
  39040. if (vDir.x >= 0.0) {
  39041. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39042. }
  39043. else {
  39044. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39045. }
  39046. this.rotation.z = 0;
  39047. if (isNaN(this.rotation.x)) {
  39048. this.rotation.x = 0;
  39049. }
  39050. if (isNaN(this.rotation.y)) {
  39051. this.rotation.y = 0;
  39052. }
  39053. if (isNaN(this.rotation.z)) {
  39054. this.rotation.z = 0;
  39055. }
  39056. if (this.rotationQuaternion) {
  39057. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39058. }
  39059. };
  39060. /**
  39061. * Return the current target position of the camera. This value is expressed in local space.
  39062. */
  39063. TargetCamera.prototype.getTarget = function () {
  39064. return this._currentTarget;
  39065. };
  39066. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39067. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39068. };
  39069. TargetCamera.prototype._updatePosition = function () {
  39070. if (this.parent) {
  39071. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39072. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39073. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39074. return;
  39075. }
  39076. this.position.addInPlace(this.cameraDirection);
  39077. };
  39078. TargetCamera.prototype._checkInputs = function () {
  39079. var needToMove = this._decideIfNeedsToMove();
  39080. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39081. // Move
  39082. if (needToMove) {
  39083. this._updatePosition();
  39084. }
  39085. // Rotate
  39086. if (needToRotate) {
  39087. this.rotation.x += this.cameraRotation.x;
  39088. this.rotation.y += this.cameraRotation.y;
  39089. //rotate, if quaternion is set and rotation was used
  39090. if (this.rotationQuaternion) {
  39091. var len = this.rotation.lengthSquared();
  39092. if (len) {
  39093. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39094. }
  39095. }
  39096. if (!this.noRotationConstraint) {
  39097. var limit = (Math.PI / 2) * 0.95;
  39098. if (this.rotation.x > limit)
  39099. this.rotation.x = limit;
  39100. if (this.rotation.x < -limit)
  39101. this.rotation.x = -limit;
  39102. }
  39103. }
  39104. // Inertia
  39105. if (needToMove) {
  39106. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39107. this.cameraDirection.x = 0;
  39108. }
  39109. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39110. this.cameraDirection.y = 0;
  39111. }
  39112. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39113. this.cameraDirection.z = 0;
  39114. }
  39115. this.cameraDirection.scaleInPlace(this.inertia);
  39116. }
  39117. if (needToRotate) {
  39118. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39119. this.cameraRotation.x = 0;
  39120. }
  39121. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39122. this.cameraRotation.y = 0;
  39123. }
  39124. this.cameraRotation.scaleInPlace(this.inertia);
  39125. }
  39126. _super.prototype._checkInputs.call(this);
  39127. };
  39128. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39129. if (this.rotationQuaternion) {
  39130. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39131. }
  39132. else {
  39133. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39134. }
  39135. //update the up vector!
  39136. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39137. };
  39138. TargetCamera.prototype._getViewMatrix = function () {
  39139. if (this.lockedTarget) {
  39140. this.setTarget(this._getLockedTargetPosition());
  39141. }
  39142. // Compute
  39143. this._updateCameraRotationMatrix();
  39144. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39145. // Computing target and final matrix
  39146. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39147. if (this.getScene().useRightHandedSystem) {
  39148. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39149. }
  39150. else {
  39151. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39152. }
  39153. return this._viewMatrix;
  39154. };
  39155. /**
  39156. * @override
  39157. * Override Camera.createRigCamera
  39158. */
  39159. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39160. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39161. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39162. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39163. if (!this.rotationQuaternion) {
  39164. this.rotationQuaternion = new BABYLON.Quaternion();
  39165. }
  39166. rigCamera._cameraRigParams = {};
  39167. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39168. }
  39169. return rigCamera;
  39170. }
  39171. return null;
  39172. };
  39173. /**
  39174. * @override
  39175. * Override Camera._updateRigCameras
  39176. */
  39177. TargetCamera.prototype._updateRigCameras = function () {
  39178. var camLeft = this._rigCameras[0];
  39179. var camRight = this._rigCameras[1];
  39180. switch (this.cameraRigMode) {
  39181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39185. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39186. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39187. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39188. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39189. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39190. camLeft.setTarget(this.getTarget());
  39191. camRight.setTarget(this.getTarget());
  39192. break;
  39193. case BABYLON.Camera.RIG_MODE_VR:
  39194. if (camLeft.rotationQuaternion) {
  39195. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39196. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39197. }
  39198. else {
  39199. camLeft.rotation.copyFrom(this.rotation);
  39200. camRight.rotation.copyFrom(this.rotation);
  39201. }
  39202. camLeft.position.copyFrom(this.position);
  39203. camRight.position.copyFrom(this.position);
  39204. break;
  39205. }
  39206. _super.prototype._updateRigCameras.call(this);
  39207. };
  39208. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39209. if (!this._rigCamTransformMatrix) {
  39210. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39211. }
  39212. var target = this.getTarget();
  39213. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39214. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39215. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39216. };
  39217. TargetCamera.prototype.getClassName = function () {
  39218. return "TargetCamera";
  39219. };
  39220. __decorate([
  39221. BABYLON.serializeAsVector3()
  39222. ], TargetCamera.prototype, "rotation", void 0);
  39223. __decorate([
  39224. BABYLON.serialize()
  39225. ], TargetCamera.prototype, "speed", void 0);
  39226. __decorate([
  39227. BABYLON.serializeAsMeshReference("lockedTargetId")
  39228. ], TargetCamera.prototype, "lockedTarget", void 0);
  39229. return TargetCamera;
  39230. }(BABYLON.Camera));
  39231. BABYLON.TargetCamera = TargetCamera;
  39232. })(BABYLON || (BABYLON = {}));
  39233. //# sourceMappingURL=babylon.targetCamera.js.map
  39234. var BABYLON;
  39235. (function (BABYLON) {
  39236. var FreeCameraMouseInput = /** @class */ (function () {
  39237. function FreeCameraMouseInput(touchEnabled) {
  39238. if (touchEnabled === void 0) { touchEnabled = true; }
  39239. this.touchEnabled = touchEnabled;
  39240. this.buttons = [0, 1, 2];
  39241. this.angularSensibility = 2000.0;
  39242. this.previousPosition = null;
  39243. }
  39244. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39245. var _this = this;
  39246. var engine = this.camera.getEngine();
  39247. if (!this._pointerInput) {
  39248. this._pointerInput = function (p, s) {
  39249. var evt = p.event;
  39250. if (engine.isInVRExclusivePointerMode) {
  39251. return;
  39252. }
  39253. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39254. return;
  39255. }
  39256. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39257. return;
  39258. }
  39259. var srcElement = (evt.srcElement || evt.target);
  39260. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39261. try {
  39262. srcElement.setPointerCapture(evt.pointerId);
  39263. }
  39264. catch (e) {
  39265. //Nothing to do with the error. Execution will continue.
  39266. }
  39267. _this.previousPosition = {
  39268. x: evt.clientX,
  39269. y: evt.clientY
  39270. };
  39271. if (!noPreventDefault) {
  39272. evt.preventDefault();
  39273. element.focus();
  39274. }
  39275. }
  39276. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39277. try {
  39278. srcElement.releasePointerCapture(evt.pointerId);
  39279. }
  39280. catch (e) {
  39281. //Nothing to do with the error.
  39282. }
  39283. _this.previousPosition = null;
  39284. if (!noPreventDefault) {
  39285. evt.preventDefault();
  39286. }
  39287. }
  39288. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39289. if (!_this.previousPosition || engine.isPointerLock) {
  39290. return;
  39291. }
  39292. var offsetX = evt.clientX - _this.previousPosition.x;
  39293. var offsetY = evt.clientY - _this.previousPosition.y;
  39294. if (_this.camera.getScene().useRightHandedSystem) {
  39295. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39296. }
  39297. else {
  39298. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39299. }
  39300. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39301. _this.previousPosition = {
  39302. x: evt.clientX,
  39303. y: evt.clientY
  39304. };
  39305. if (!noPreventDefault) {
  39306. evt.preventDefault();
  39307. }
  39308. }
  39309. };
  39310. }
  39311. this._onMouseMove = function (evt) {
  39312. if (!engine.isPointerLock) {
  39313. return;
  39314. }
  39315. if (engine.isInVRExclusivePointerMode) {
  39316. return;
  39317. }
  39318. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39319. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39320. if (_this.camera.getScene().useRightHandedSystem) {
  39321. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39322. }
  39323. else {
  39324. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39325. }
  39326. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39327. _this.previousPosition = null;
  39328. if (!noPreventDefault) {
  39329. evt.preventDefault();
  39330. }
  39331. };
  39332. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39333. element.addEventListener("mousemove", this._onMouseMove, false);
  39334. };
  39335. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39336. if (this._observer && element) {
  39337. this.camera.getScene().onPointerObservable.remove(this._observer);
  39338. if (this._onMouseMove) {
  39339. element.removeEventListener("mousemove", this._onMouseMove);
  39340. }
  39341. this._observer = null;
  39342. this._onMouseMove = null;
  39343. this.previousPosition = null;
  39344. }
  39345. };
  39346. FreeCameraMouseInput.prototype.getClassName = function () {
  39347. return "FreeCameraMouseInput";
  39348. };
  39349. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39350. return "mouse";
  39351. };
  39352. __decorate([
  39353. BABYLON.serialize()
  39354. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39355. __decorate([
  39356. BABYLON.serialize()
  39357. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39358. return FreeCameraMouseInput;
  39359. }());
  39360. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39361. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39362. })(BABYLON || (BABYLON = {}));
  39363. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39364. var BABYLON;
  39365. (function (BABYLON) {
  39366. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39367. function FreeCameraKeyboardMoveInput() {
  39368. this._keys = new Array();
  39369. this.keysUp = [38];
  39370. this.keysDown = [40];
  39371. this.keysLeft = [37];
  39372. this.keysRight = [39];
  39373. }
  39374. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39375. var _this = this;
  39376. if (this._onCanvasBlurObserver) {
  39377. return;
  39378. }
  39379. this._scene = this.camera.getScene();
  39380. this._engine = this._scene.getEngine();
  39381. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39382. _this._keys = [];
  39383. });
  39384. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39385. var evt = info.event;
  39386. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39390. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39391. var index = _this._keys.indexOf(evt.keyCode);
  39392. if (index === -1) {
  39393. _this._keys.push(evt.keyCode);
  39394. }
  39395. if (!noPreventDefault) {
  39396. evt.preventDefault();
  39397. }
  39398. }
  39399. }
  39400. else {
  39401. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39402. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39403. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39404. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39405. var index = _this._keys.indexOf(evt.keyCode);
  39406. if (index >= 0) {
  39407. _this._keys.splice(index, 1);
  39408. }
  39409. if (!noPreventDefault) {
  39410. evt.preventDefault();
  39411. }
  39412. }
  39413. }
  39414. });
  39415. };
  39416. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39417. if (this._scene) {
  39418. if (this._onKeyboardObserver) {
  39419. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39420. }
  39421. if (this._onCanvasBlurObserver) {
  39422. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39423. }
  39424. this._onKeyboardObserver = null;
  39425. this._onCanvasBlurObserver = null;
  39426. }
  39427. this._keys = [];
  39428. };
  39429. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39430. if (this._onKeyboardObserver) {
  39431. var camera = this.camera;
  39432. // Keyboard
  39433. for (var index = 0; index < this._keys.length; index++) {
  39434. var keyCode = this._keys[index];
  39435. var speed = camera._computeLocalCameraSpeed();
  39436. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39437. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39438. }
  39439. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39440. camera._localDirection.copyFromFloats(0, 0, speed);
  39441. }
  39442. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39443. camera._localDirection.copyFromFloats(speed, 0, 0);
  39444. }
  39445. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39446. camera._localDirection.copyFromFloats(0, 0, -speed);
  39447. }
  39448. if (camera.getScene().useRightHandedSystem) {
  39449. camera._localDirection.z *= -1;
  39450. }
  39451. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39452. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39453. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39454. }
  39455. }
  39456. };
  39457. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39458. return "FreeCameraKeyboardMoveInput";
  39459. };
  39460. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39461. this._keys = [];
  39462. };
  39463. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39464. return "keyboard";
  39465. };
  39466. __decorate([
  39467. BABYLON.serialize()
  39468. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39469. __decorate([
  39470. BABYLON.serialize()
  39471. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39472. __decorate([
  39473. BABYLON.serialize()
  39474. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39475. __decorate([
  39476. BABYLON.serialize()
  39477. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39478. return FreeCameraKeyboardMoveInput;
  39479. }());
  39480. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39481. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39482. })(BABYLON || (BABYLON = {}));
  39483. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39484. var BABYLON;
  39485. (function (BABYLON) {
  39486. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39487. __extends(FreeCameraInputsManager, _super);
  39488. function FreeCameraInputsManager(camera) {
  39489. return _super.call(this, camera) || this;
  39490. }
  39491. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39492. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39493. return this;
  39494. };
  39495. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39496. if (touchEnabled === void 0) { touchEnabled = true; }
  39497. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39498. return this;
  39499. };
  39500. FreeCameraInputsManager.prototype.addGamepad = function () {
  39501. this.add(new BABYLON.FreeCameraGamepadInput());
  39502. return this;
  39503. };
  39504. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39505. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39506. return this;
  39507. };
  39508. FreeCameraInputsManager.prototype.addTouch = function () {
  39509. this.add(new BABYLON.FreeCameraTouchInput());
  39510. return this;
  39511. };
  39512. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39513. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39514. return this;
  39515. };
  39516. return FreeCameraInputsManager;
  39517. }(BABYLON.CameraInputsManager));
  39518. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39519. })(BABYLON || (BABYLON = {}));
  39520. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39521. var BABYLON;
  39522. (function (BABYLON) {
  39523. var FreeCamera = /** @class */ (function (_super) {
  39524. __extends(FreeCamera, _super);
  39525. function FreeCamera(name, position, scene) {
  39526. var _this = _super.call(this, name, position, scene) || this;
  39527. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39528. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39529. _this.checkCollisions = false;
  39530. _this.applyGravity = false;
  39531. _this._needMoveForGravity = false;
  39532. _this._oldPosition = BABYLON.Vector3.Zero();
  39533. _this._diffPosition = BABYLON.Vector3.Zero();
  39534. _this._newPosition = BABYLON.Vector3.Zero();
  39535. // Collisions
  39536. _this._collisionMask = -1;
  39537. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39538. if (collidedMesh === void 0) { collidedMesh = null; }
  39539. //TODO move this to the collision coordinator!
  39540. if (_this.getScene().workerCollisions)
  39541. newPosition.multiplyInPlace(_this._collider._radius);
  39542. var updatePosition = function (newPos) {
  39543. _this._newPosition.copyFrom(newPos);
  39544. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39545. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39546. _this.position.addInPlace(_this._diffPosition);
  39547. if (_this.onCollide && collidedMesh) {
  39548. _this.onCollide(collidedMesh);
  39549. }
  39550. }
  39551. };
  39552. updatePosition(newPosition);
  39553. };
  39554. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39555. _this.inputs.addKeyboard().addMouse();
  39556. return _this;
  39557. }
  39558. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39559. //-- begin properties for backward compatibility for inputs
  39560. get: function () {
  39561. var mouse = this.inputs.attached["mouse"];
  39562. if (mouse)
  39563. return mouse.angularSensibility;
  39564. return 0;
  39565. },
  39566. set: function (value) {
  39567. var mouse = this.inputs.attached["mouse"];
  39568. if (mouse)
  39569. mouse.angularSensibility = value;
  39570. },
  39571. enumerable: true,
  39572. configurable: true
  39573. });
  39574. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39575. get: function () {
  39576. var keyboard = this.inputs.attached["keyboard"];
  39577. if (keyboard)
  39578. return keyboard.keysUp;
  39579. return [];
  39580. },
  39581. set: function (value) {
  39582. var keyboard = this.inputs.attached["keyboard"];
  39583. if (keyboard)
  39584. keyboard.keysUp = value;
  39585. },
  39586. enumerable: true,
  39587. configurable: true
  39588. });
  39589. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39590. get: function () {
  39591. var keyboard = this.inputs.attached["keyboard"];
  39592. if (keyboard)
  39593. return keyboard.keysDown;
  39594. return [];
  39595. },
  39596. set: function (value) {
  39597. var keyboard = this.inputs.attached["keyboard"];
  39598. if (keyboard)
  39599. keyboard.keysDown = value;
  39600. },
  39601. enumerable: true,
  39602. configurable: true
  39603. });
  39604. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39605. get: function () {
  39606. var keyboard = this.inputs.attached["keyboard"];
  39607. if (keyboard)
  39608. return keyboard.keysLeft;
  39609. return [];
  39610. },
  39611. set: function (value) {
  39612. var keyboard = this.inputs.attached["keyboard"];
  39613. if (keyboard)
  39614. keyboard.keysLeft = value;
  39615. },
  39616. enumerable: true,
  39617. configurable: true
  39618. });
  39619. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39620. get: function () {
  39621. var keyboard = this.inputs.attached["keyboard"];
  39622. if (keyboard)
  39623. return keyboard.keysRight;
  39624. return [];
  39625. },
  39626. set: function (value) {
  39627. var keyboard = this.inputs.attached["keyboard"];
  39628. if (keyboard)
  39629. keyboard.keysRight = value;
  39630. },
  39631. enumerable: true,
  39632. configurable: true
  39633. });
  39634. // Controls
  39635. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39636. this.inputs.attachElement(element, noPreventDefault);
  39637. };
  39638. FreeCamera.prototype.detachControl = function (element) {
  39639. this.inputs.detachElement(element);
  39640. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39641. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39642. };
  39643. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39644. get: function () {
  39645. return this._collisionMask;
  39646. },
  39647. set: function (mask) {
  39648. this._collisionMask = !isNaN(mask) ? mask : -1;
  39649. },
  39650. enumerable: true,
  39651. configurable: true
  39652. });
  39653. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39654. var globalPosition;
  39655. if (this.parent) {
  39656. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39657. }
  39658. else {
  39659. globalPosition = this.position;
  39660. }
  39661. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39662. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39663. if (!this._collider) {
  39664. this._collider = new BABYLON.Collider();
  39665. }
  39666. this._collider._radius = this.ellipsoid;
  39667. this._collider.collisionMask = this._collisionMask;
  39668. //no need for clone, as long as gravity is not on.
  39669. var actualDisplacement = displacement;
  39670. //add gravity to the direction to prevent the dual-collision checking
  39671. if (this.applyGravity) {
  39672. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39673. actualDisplacement = displacement.add(this.getScene().gravity);
  39674. }
  39675. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39676. };
  39677. FreeCamera.prototype._checkInputs = function () {
  39678. if (!this._localDirection) {
  39679. this._localDirection = BABYLON.Vector3.Zero();
  39680. this._transformedDirection = BABYLON.Vector3.Zero();
  39681. }
  39682. this.inputs.checkInputs();
  39683. _super.prototype._checkInputs.call(this);
  39684. };
  39685. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39686. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39687. };
  39688. FreeCamera.prototype._updatePosition = function () {
  39689. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39690. this._collideWithWorld(this.cameraDirection);
  39691. }
  39692. else {
  39693. _super.prototype._updatePosition.call(this);
  39694. }
  39695. };
  39696. FreeCamera.prototype.dispose = function () {
  39697. this.inputs.clear();
  39698. _super.prototype.dispose.call(this);
  39699. };
  39700. FreeCamera.prototype.getClassName = function () {
  39701. return "FreeCamera";
  39702. };
  39703. __decorate([
  39704. BABYLON.serializeAsVector3()
  39705. ], FreeCamera.prototype, "ellipsoid", void 0);
  39706. __decorate([
  39707. BABYLON.serializeAsVector3()
  39708. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39709. __decorate([
  39710. BABYLON.serialize()
  39711. ], FreeCamera.prototype, "checkCollisions", void 0);
  39712. __decorate([
  39713. BABYLON.serialize()
  39714. ], FreeCamera.prototype, "applyGravity", void 0);
  39715. return FreeCamera;
  39716. }(BABYLON.TargetCamera));
  39717. BABYLON.FreeCamera = FreeCamera;
  39718. })(BABYLON || (BABYLON = {}));
  39719. //# sourceMappingURL=babylon.freeCamera.js.map
  39720. var BABYLON;
  39721. (function (BABYLON) {
  39722. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39723. function ArcRotateCameraKeyboardMoveInput() {
  39724. this._keys = new Array();
  39725. this.keysUp = [38];
  39726. this.keysDown = [40];
  39727. this.keysLeft = [37];
  39728. this.keysRight = [39];
  39729. this.keysReset = [220];
  39730. this.panningSensibility = 50.0;
  39731. this.zoomingSensibility = 25.0;
  39732. this.useAltToZoom = true;
  39733. }
  39734. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39735. var _this = this;
  39736. if (this._onCanvasBlurObserver) {
  39737. return;
  39738. }
  39739. this._scene = this.camera.getScene();
  39740. this._engine = this._scene.getEngine();
  39741. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39742. _this._keys = [];
  39743. });
  39744. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39745. var evt = info.event;
  39746. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39747. _this._ctrlPressed = evt.ctrlKey;
  39748. _this._altPressed = evt.altKey;
  39749. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39750. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39751. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39752. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39753. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39754. var index = _this._keys.indexOf(evt.keyCode);
  39755. if (index === -1) {
  39756. _this._keys.push(evt.keyCode);
  39757. }
  39758. if (evt.preventDefault) {
  39759. if (!noPreventDefault) {
  39760. evt.preventDefault();
  39761. }
  39762. }
  39763. }
  39764. }
  39765. else {
  39766. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39767. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39768. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39769. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39770. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39771. var index = _this._keys.indexOf(evt.keyCode);
  39772. if (index >= 0) {
  39773. _this._keys.splice(index, 1);
  39774. }
  39775. if (evt.preventDefault) {
  39776. if (!noPreventDefault) {
  39777. evt.preventDefault();
  39778. }
  39779. }
  39780. }
  39781. }
  39782. });
  39783. };
  39784. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39785. if (this._scene) {
  39786. if (this._onKeyboardObserver) {
  39787. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39788. }
  39789. if (this._onCanvasBlurObserver) {
  39790. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39791. }
  39792. this._onKeyboardObserver = null;
  39793. this._onCanvasBlurObserver = null;
  39794. }
  39795. this._keys = [];
  39796. };
  39797. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39798. if (this._onKeyboardObserver) {
  39799. var camera = this.camera;
  39800. for (var index = 0; index < this._keys.length; index++) {
  39801. var keyCode = this._keys[index];
  39802. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39803. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39804. camera.inertialPanningX -= 1 / this.panningSensibility;
  39805. }
  39806. else {
  39807. camera.inertialAlphaOffset -= 0.01;
  39808. }
  39809. }
  39810. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39811. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39812. camera.inertialPanningY += 1 / this.panningSensibility;
  39813. }
  39814. else if (this._altPressed && this.useAltToZoom) {
  39815. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39816. }
  39817. else {
  39818. camera.inertialBetaOffset -= 0.01;
  39819. }
  39820. }
  39821. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39822. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39823. camera.inertialPanningX += 1 / this.panningSensibility;
  39824. }
  39825. else {
  39826. camera.inertialAlphaOffset += 0.01;
  39827. }
  39828. }
  39829. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39830. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39831. camera.inertialPanningY -= 1 / this.panningSensibility;
  39832. }
  39833. else if (this._altPressed && this.useAltToZoom) {
  39834. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39835. }
  39836. else {
  39837. camera.inertialBetaOffset += 0.01;
  39838. }
  39839. }
  39840. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39841. camera.restoreState();
  39842. }
  39843. }
  39844. }
  39845. };
  39846. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39847. return "ArcRotateCameraKeyboardMoveInput";
  39848. };
  39849. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39850. return "keyboard";
  39851. };
  39852. __decorate([
  39853. BABYLON.serialize()
  39854. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39855. __decorate([
  39856. BABYLON.serialize()
  39857. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39858. __decorate([
  39859. BABYLON.serialize()
  39860. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39861. __decorate([
  39862. BABYLON.serialize()
  39863. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39864. __decorate([
  39865. BABYLON.serialize()
  39866. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39867. __decorate([
  39868. BABYLON.serialize()
  39869. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39870. __decorate([
  39871. BABYLON.serialize()
  39872. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39873. __decorate([
  39874. BABYLON.serialize()
  39875. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39876. return ArcRotateCameraKeyboardMoveInput;
  39877. }());
  39878. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39879. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39880. })(BABYLON || (BABYLON = {}));
  39881. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39882. var BABYLON;
  39883. (function (BABYLON) {
  39884. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39885. function ArcRotateCameraMouseWheelInput() {
  39886. this.wheelPrecision = 3.0;
  39887. /**
  39888. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39889. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39890. */
  39891. this.wheelDeltaPercentage = 0;
  39892. }
  39893. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39894. var _this = this;
  39895. this._wheel = function (p, s) {
  39896. //sanity check - this should be a PointerWheel event.
  39897. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39898. return;
  39899. var event = p.event;
  39900. var delta = 0;
  39901. if (event.wheelDelta) {
  39902. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39903. }
  39904. else if (event.detail) {
  39905. delta = -event.detail / _this.wheelPrecision;
  39906. }
  39907. if (delta)
  39908. _this.camera.inertialRadiusOffset += delta;
  39909. if (event.preventDefault) {
  39910. if (!noPreventDefault) {
  39911. event.preventDefault();
  39912. }
  39913. }
  39914. };
  39915. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39916. };
  39917. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39918. if (this._observer && element) {
  39919. this.camera.getScene().onPointerObservable.remove(this._observer);
  39920. this._observer = null;
  39921. this._wheel = null;
  39922. }
  39923. };
  39924. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39925. return "ArcRotateCameraMouseWheelInput";
  39926. };
  39927. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39928. return "mousewheel";
  39929. };
  39930. __decorate([
  39931. BABYLON.serialize()
  39932. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39933. __decorate([
  39934. BABYLON.serialize()
  39935. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39936. return ArcRotateCameraMouseWheelInput;
  39937. }());
  39938. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39939. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39940. })(BABYLON || (BABYLON = {}));
  39941. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39942. var BABYLON;
  39943. (function (BABYLON) {
  39944. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39945. function ArcRotateCameraPointersInput() {
  39946. this.buttons = [0, 1, 2];
  39947. this.angularSensibilityX = 1000.0;
  39948. this.angularSensibilityY = 1000.0;
  39949. this.pinchPrecision = 12.0;
  39950. /**
  39951. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39952. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39953. */
  39954. this.pinchDeltaPercentage = 0;
  39955. this.panningSensibility = 1000.0;
  39956. this.multiTouchPanning = true;
  39957. this.multiTouchPanAndZoom = true;
  39958. this._isPanClick = false;
  39959. this.pinchInwards = true;
  39960. }
  39961. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39962. var _this = this;
  39963. var engine = this.camera.getEngine();
  39964. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39965. var pointA = null;
  39966. var pointB = null;
  39967. var previousPinchSquaredDistance = 0;
  39968. var initialDistance = 0;
  39969. var twoFingerActivityCount = 0;
  39970. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39971. this._pointerInput = function (p, s) {
  39972. var evt = p.event;
  39973. var isTouch = p.event.pointerType === "touch";
  39974. if (engine.isInVRExclusivePointerMode) {
  39975. return;
  39976. }
  39977. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39978. return;
  39979. }
  39980. var srcElement = (evt.srcElement || evt.target);
  39981. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39982. try {
  39983. srcElement.setPointerCapture(evt.pointerId);
  39984. }
  39985. catch (e) {
  39986. //Nothing to do with the error. Execution will continue.
  39987. }
  39988. // Manage panning with pan button click
  39989. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39990. // manage pointers
  39991. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39992. if (pointA === null) {
  39993. pointA = cacheSoloPointer;
  39994. }
  39995. else if (pointB === null) {
  39996. pointB = cacheSoloPointer;
  39997. }
  39998. if (!noPreventDefault) {
  39999. evt.preventDefault();
  40000. element.focus();
  40001. }
  40002. }
  40003. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40004. _this.camera.restoreState();
  40005. }
  40006. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40007. try {
  40008. srcElement.releasePointerCapture(evt.pointerId);
  40009. }
  40010. catch (e) {
  40011. //Nothing to do with the error.
  40012. }
  40013. cacheSoloPointer = null;
  40014. previousPinchSquaredDistance = 0;
  40015. previousMultiTouchPanPosition.isPaning = false;
  40016. previousMultiTouchPanPosition.isPinching = false;
  40017. twoFingerActivityCount = 0;
  40018. initialDistance = 0;
  40019. if (!isTouch) {
  40020. pointB = null; // Mouse and pen are mono pointer
  40021. }
  40022. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40023. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40024. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40025. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40026. if (engine.badOS) {
  40027. pointA = pointB = null;
  40028. }
  40029. else {
  40030. //only remove the impacted pointer in case of multitouch allowing on most
  40031. //platforms switching from rotate to zoom and pan seamlessly.
  40032. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40033. pointA = pointB;
  40034. pointB = null;
  40035. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40036. }
  40037. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40038. pointB = null;
  40039. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40040. }
  40041. else {
  40042. pointA = pointB = null;
  40043. }
  40044. }
  40045. if (!noPreventDefault) {
  40046. evt.preventDefault();
  40047. }
  40048. }
  40049. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40050. if (!noPreventDefault) {
  40051. evt.preventDefault();
  40052. }
  40053. // One button down
  40054. if (pointA && pointB === null && cacheSoloPointer) {
  40055. if (_this.panningSensibility !== 0 &&
  40056. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40057. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40058. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40059. }
  40060. else {
  40061. var offsetX = evt.clientX - cacheSoloPointer.x;
  40062. var offsetY = evt.clientY - cacheSoloPointer.y;
  40063. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40064. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40065. }
  40066. cacheSoloPointer.x = evt.clientX;
  40067. cacheSoloPointer.y = evt.clientY;
  40068. }
  40069. else if (pointA && pointB) {
  40070. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40071. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40072. ed.x = evt.clientX;
  40073. ed.y = evt.clientY;
  40074. var direction = _this.pinchInwards ? 1 : -1;
  40075. var distX = pointA.x - pointB.x;
  40076. var distY = pointA.y - pointB.y;
  40077. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40078. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40079. if (previousPinchSquaredDistance === 0) {
  40080. initialDistance = pinchDistance;
  40081. previousPinchSquaredDistance = pinchSquaredDistance;
  40082. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40083. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40084. return;
  40085. }
  40086. if (_this.multiTouchPanAndZoom) {
  40087. if (_this.pinchDeltaPercentage) {
  40088. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40089. }
  40090. else {
  40091. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40092. (_this.pinchPrecision *
  40093. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40094. direction);
  40095. }
  40096. if (_this.panningSensibility !== 0) {
  40097. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40098. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40099. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40100. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40101. previousMultiTouchPanPosition.x = pointersCenterX;
  40102. previousMultiTouchPanPosition.y = pointersCenterY;
  40103. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40104. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40105. }
  40106. }
  40107. else {
  40108. twoFingerActivityCount++;
  40109. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40110. if (_this.pinchDeltaPercentage) {
  40111. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40112. }
  40113. else {
  40114. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40115. (_this.pinchPrecision *
  40116. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40117. direction);
  40118. }
  40119. previousMultiTouchPanPosition.isPaning = false;
  40120. previousMultiTouchPanPosition.isPinching = true;
  40121. }
  40122. else {
  40123. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40124. if (!previousMultiTouchPanPosition.isPaning) {
  40125. previousMultiTouchPanPosition.isPaning = true;
  40126. previousMultiTouchPanPosition.isPinching = false;
  40127. previousMultiTouchPanPosition.x = ed.x;
  40128. previousMultiTouchPanPosition.y = ed.y;
  40129. return;
  40130. }
  40131. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40132. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40133. }
  40134. }
  40135. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40136. previousMultiTouchPanPosition.x = ed.x;
  40137. previousMultiTouchPanPosition.y = ed.y;
  40138. }
  40139. }
  40140. previousPinchSquaredDistance = pinchSquaredDistance;
  40141. }
  40142. }
  40143. };
  40144. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40145. this._onContextMenu = function (evt) {
  40146. evt.preventDefault();
  40147. };
  40148. if (!this.camera._useCtrlForPanning) {
  40149. element.addEventListener("contextmenu", this._onContextMenu, false);
  40150. }
  40151. this._onLostFocus = function () {
  40152. //this._keys = [];
  40153. pointA = pointB = null;
  40154. previousPinchSquaredDistance = 0;
  40155. previousMultiTouchPanPosition.isPaning = false;
  40156. previousMultiTouchPanPosition.isPinching = false;
  40157. twoFingerActivityCount = 0;
  40158. cacheSoloPointer = null;
  40159. initialDistance = 0;
  40160. };
  40161. this._onMouseMove = function (evt) {
  40162. if (!engine.isPointerLock) {
  40163. return;
  40164. }
  40165. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40166. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40167. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40168. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40169. if (!noPreventDefault) {
  40170. evt.preventDefault();
  40171. }
  40172. };
  40173. this._onGestureStart = function (e) {
  40174. if (window.MSGesture === undefined) {
  40175. return;
  40176. }
  40177. if (!_this._MSGestureHandler) {
  40178. _this._MSGestureHandler = new MSGesture();
  40179. _this._MSGestureHandler.target = element;
  40180. }
  40181. _this._MSGestureHandler.addPointer(e.pointerId);
  40182. };
  40183. this._onGesture = function (e) {
  40184. _this.camera.radius *= e.scale;
  40185. if (e.preventDefault) {
  40186. if (!noPreventDefault) {
  40187. e.stopPropagation();
  40188. e.preventDefault();
  40189. }
  40190. }
  40191. };
  40192. element.addEventListener("mousemove", this._onMouseMove, false);
  40193. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40194. element.addEventListener("MSGestureChange", this._onGesture, false);
  40195. BABYLON.Tools.RegisterTopRootEvents([
  40196. { name: "blur", handler: this._onLostFocus }
  40197. ]);
  40198. };
  40199. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40200. if (this._onLostFocus) {
  40201. BABYLON.Tools.UnregisterTopRootEvents([
  40202. { name: "blur", handler: this._onLostFocus }
  40203. ]);
  40204. }
  40205. if (element && this._observer) {
  40206. this.camera.getScene().onPointerObservable.remove(this._observer);
  40207. this._observer = null;
  40208. if (this._onContextMenu) {
  40209. element.removeEventListener("contextmenu", this._onContextMenu);
  40210. }
  40211. if (this._onMouseMove) {
  40212. element.removeEventListener("mousemove", this._onMouseMove);
  40213. }
  40214. if (this._onGestureStart) {
  40215. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40216. }
  40217. if (this._onGesture) {
  40218. element.removeEventListener("MSGestureChange", this._onGesture);
  40219. }
  40220. this._isPanClick = false;
  40221. this.pinchInwards = true;
  40222. this._onMouseMove = null;
  40223. this._onGestureStart = null;
  40224. this._onGesture = null;
  40225. this._MSGestureHandler = null;
  40226. this._onLostFocus = null;
  40227. this._onContextMenu = null;
  40228. }
  40229. };
  40230. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40231. return "ArcRotateCameraPointersInput";
  40232. };
  40233. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40234. return "pointers";
  40235. };
  40236. __decorate([
  40237. BABYLON.serialize()
  40238. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40239. __decorate([
  40240. BABYLON.serialize()
  40241. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40242. __decorate([
  40243. BABYLON.serialize()
  40244. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40245. __decorate([
  40246. BABYLON.serialize()
  40247. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40248. __decorate([
  40249. BABYLON.serialize()
  40250. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40251. __decorate([
  40252. BABYLON.serialize()
  40253. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40254. __decorate([
  40255. BABYLON.serialize()
  40256. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40257. __decorate([
  40258. BABYLON.serialize()
  40259. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40260. return ArcRotateCameraPointersInput;
  40261. }());
  40262. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40263. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40264. })(BABYLON || (BABYLON = {}));
  40265. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40266. var BABYLON;
  40267. (function (BABYLON) {
  40268. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40269. __extends(ArcRotateCameraInputsManager, _super);
  40270. function ArcRotateCameraInputsManager(camera) {
  40271. return _super.call(this, camera) || this;
  40272. }
  40273. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40274. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40275. return this;
  40276. };
  40277. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40278. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40279. return this;
  40280. };
  40281. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40282. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40283. return this;
  40284. };
  40285. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40286. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40287. return this;
  40288. };
  40289. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40290. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40291. return this;
  40292. };
  40293. return ArcRotateCameraInputsManager;
  40294. }(BABYLON.CameraInputsManager));
  40295. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40296. })(BABYLON || (BABYLON = {}));
  40297. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40298. var BABYLON;
  40299. (function (BABYLON) {
  40300. var ArcRotateCamera = /** @class */ (function (_super) {
  40301. __extends(ArcRotateCamera, _super);
  40302. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40303. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40304. _this.inertialAlphaOffset = 0;
  40305. _this.inertialBetaOffset = 0;
  40306. _this.inertialRadiusOffset = 0;
  40307. _this.lowerAlphaLimit = null;
  40308. _this.upperAlphaLimit = null;
  40309. _this.lowerBetaLimit = 0.01;
  40310. _this.upperBetaLimit = Math.PI;
  40311. _this.lowerRadiusLimit = null;
  40312. _this.upperRadiusLimit = null;
  40313. _this.inertialPanningX = 0;
  40314. _this.inertialPanningY = 0;
  40315. _this.pinchToPanMaxDistance = 20;
  40316. _this.panningDistanceLimit = null;
  40317. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40318. _this.panningInertia = 0.9;
  40319. //-- end properties for backward compatibility for inputs
  40320. _this.zoomOnFactor = 1;
  40321. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40322. _this.allowUpsideDown = true;
  40323. _this._viewMatrix = new BABYLON.Matrix();
  40324. // Panning
  40325. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40326. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40327. _this.checkCollisions = false;
  40328. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40329. _this._previousPosition = BABYLON.Vector3.Zero();
  40330. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40331. _this._newPosition = BABYLON.Vector3.Zero();
  40332. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40333. if (collidedMesh === void 0) { collidedMesh = null; }
  40334. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40335. newPosition.multiplyInPlace(_this._collider._radius);
  40336. }
  40337. if (!collidedMesh) {
  40338. _this._previousPosition.copyFrom(_this.position);
  40339. }
  40340. else {
  40341. _this.setPosition(newPosition);
  40342. if (_this.onCollide) {
  40343. _this.onCollide(collidedMesh);
  40344. }
  40345. }
  40346. // Recompute because of constraints
  40347. var cosa = Math.cos(_this.alpha);
  40348. var sina = Math.sin(_this.alpha);
  40349. var cosb = Math.cos(_this.beta);
  40350. var sinb = Math.sin(_this.beta);
  40351. if (sinb === 0) {
  40352. sinb = 0.0001;
  40353. }
  40354. var target = _this._getTargetPosition();
  40355. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40356. _this.position.copyFrom(_this._newPosition);
  40357. var up = _this.upVector;
  40358. if (_this.allowUpsideDown && _this.beta < 0) {
  40359. up = up.clone();
  40360. up = up.negate();
  40361. }
  40362. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40363. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40364. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40365. _this._collisionTriggered = false;
  40366. };
  40367. _this._target = BABYLON.Vector3.Zero();
  40368. if (target) {
  40369. _this.setTarget(target);
  40370. }
  40371. _this.alpha = alpha;
  40372. _this.beta = beta;
  40373. _this.radius = radius;
  40374. _this.getViewMatrix();
  40375. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40376. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40377. return _this;
  40378. }
  40379. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40380. get: function () {
  40381. return this._target;
  40382. },
  40383. set: function (value) {
  40384. this.setTarget(value);
  40385. },
  40386. enumerable: true,
  40387. configurable: true
  40388. });
  40389. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40390. //-- begin properties for backward compatibility for inputs
  40391. get: function () {
  40392. var pointers = this.inputs.attached["pointers"];
  40393. if (pointers)
  40394. return pointers.angularSensibilityX;
  40395. return 0;
  40396. },
  40397. set: function (value) {
  40398. var pointers = this.inputs.attached["pointers"];
  40399. if (pointers) {
  40400. pointers.angularSensibilityX = value;
  40401. }
  40402. },
  40403. enumerable: true,
  40404. configurable: true
  40405. });
  40406. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40407. get: function () {
  40408. var pointers = this.inputs.attached["pointers"];
  40409. if (pointers)
  40410. return pointers.angularSensibilityY;
  40411. return 0;
  40412. },
  40413. set: function (value) {
  40414. var pointers = this.inputs.attached["pointers"];
  40415. if (pointers) {
  40416. pointers.angularSensibilityY = value;
  40417. }
  40418. },
  40419. enumerable: true,
  40420. configurable: true
  40421. });
  40422. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40423. get: function () {
  40424. var pointers = this.inputs.attached["pointers"];
  40425. if (pointers)
  40426. return pointers.pinchPrecision;
  40427. return 0;
  40428. },
  40429. set: function (value) {
  40430. var pointers = this.inputs.attached["pointers"];
  40431. if (pointers) {
  40432. pointers.pinchPrecision = value;
  40433. }
  40434. },
  40435. enumerable: true,
  40436. configurable: true
  40437. });
  40438. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40439. get: function () {
  40440. var pointers = this.inputs.attached["pointers"];
  40441. if (pointers)
  40442. return pointers.pinchDeltaPercentage;
  40443. return 0;
  40444. },
  40445. set: function (value) {
  40446. var pointers = this.inputs.attached["pointers"];
  40447. if (pointers) {
  40448. pointers.pinchDeltaPercentage = value;
  40449. }
  40450. },
  40451. enumerable: true,
  40452. configurable: true
  40453. });
  40454. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40455. get: function () {
  40456. var pointers = this.inputs.attached["pointers"];
  40457. if (pointers)
  40458. return pointers.panningSensibility;
  40459. return 0;
  40460. },
  40461. set: function (value) {
  40462. var pointers = this.inputs.attached["pointers"];
  40463. if (pointers) {
  40464. pointers.panningSensibility = value;
  40465. }
  40466. },
  40467. enumerable: true,
  40468. configurable: true
  40469. });
  40470. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40471. get: function () {
  40472. var keyboard = this.inputs.attached["keyboard"];
  40473. if (keyboard)
  40474. return keyboard.keysUp;
  40475. return [];
  40476. },
  40477. set: function (value) {
  40478. var keyboard = this.inputs.attached["keyboard"];
  40479. if (keyboard)
  40480. keyboard.keysUp = value;
  40481. },
  40482. enumerable: true,
  40483. configurable: true
  40484. });
  40485. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40486. get: function () {
  40487. var keyboard = this.inputs.attached["keyboard"];
  40488. if (keyboard)
  40489. return keyboard.keysDown;
  40490. return [];
  40491. },
  40492. set: function (value) {
  40493. var keyboard = this.inputs.attached["keyboard"];
  40494. if (keyboard)
  40495. keyboard.keysDown = value;
  40496. },
  40497. enumerable: true,
  40498. configurable: true
  40499. });
  40500. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40501. get: function () {
  40502. var keyboard = this.inputs.attached["keyboard"];
  40503. if (keyboard)
  40504. return keyboard.keysLeft;
  40505. return [];
  40506. },
  40507. set: function (value) {
  40508. var keyboard = this.inputs.attached["keyboard"];
  40509. if (keyboard)
  40510. keyboard.keysLeft = value;
  40511. },
  40512. enumerable: true,
  40513. configurable: true
  40514. });
  40515. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40516. get: function () {
  40517. var keyboard = this.inputs.attached["keyboard"];
  40518. if (keyboard)
  40519. return keyboard.keysRight;
  40520. return [];
  40521. },
  40522. set: function (value) {
  40523. var keyboard = this.inputs.attached["keyboard"];
  40524. if (keyboard)
  40525. keyboard.keysRight = value;
  40526. },
  40527. enumerable: true,
  40528. configurable: true
  40529. });
  40530. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40531. get: function () {
  40532. var mousewheel = this.inputs.attached["mousewheel"];
  40533. if (mousewheel)
  40534. return mousewheel.wheelPrecision;
  40535. return 0;
  40536. },
  40537. set: function (value) {
  40538. var mousewheel = this.inputs.attached["mousewheel"];
  40539. if (mousewheel)
  40540. mousewheel.wheelPrecision = value;
  40541. },
  40542. enumerable: true,
  40543. configurable: true
  40544. });
  40545. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40546. get: function () {
  40547. var mousewheel = this.inputs.attached["mousewheel"];
  40548. if (mousewheel)
  40549. return mousewheel.wheelDeltaPercentage;
  40550. return 0;
  40551. },
  40552. set: function (value) {
  40553. var mousewheel = this.inputs.attached["mousewheel"];
  40554. if (mousewheel)
  40555. mousewheel.wheelDeltaPercentage = value;
  40556. },
  40557. enumerable: true,
  40558. configurable: true
  40559. });
  40560. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40561. get: function () {
  40562. return this._bouncingBehavior;
  40563. },
  40564. enumerable: true,
  40565. configurable: true
  40566. });
  40567. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40568. get: function () {
  40569. return this._bouncingBehavior != null;
  40570. },
  40571. set: function (value) {
  40572. if (value === this.useBouncingBehavior) {
  40573. return;
  40574. }
  40575. if (value) {
  40576. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40577. this.addBehavior(this._bouncingBehavior);
  40578. }
  40579. else if (this._bouncingBehavior) {
  40580. this.removeBehavior(this._bouncingBehavior);
  40581. this._bouncingBehavior = null;
  40582. }
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40588. get: function () {
  40589. return this._framingBehavior;
  40590. },
  40591. enumerable: true,
  40592. configurable: true
  40593. });
  40594. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40595. get: function () {
  40596. return this._framingBehavior != null;
  40597. },
  40598. set: function (value) {
  40599. if (value === this.useFramingBehavior) {
  40600. return;
  40601. }
  40602. if (value) {
  40603. this._framingBehavior = new BABYLON.FramingBehavior();
  40604. this.addBehavior(this._framingBehavior);
  40605. }
  40606. else if (this._framingBehavior) {
  40607. this.removeBehavior(this._framingBehavior);
  40608. this._framingBehavior = null;
  40609. }
  40610. },
  40611. enumerable: true,
  40612. configurable: true
  40613. });
  40614. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40615. get: function () {
  40616. return this._autoRotationBehavior;
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40622. get: function () {
  40623. return this._autoRotationBehavior != null;
  40624. },
  40625. set: function (value) {
  40626. if (value === this.useAutoRotationBehavior) {
  40627. return;
  40628. }
  40629. if (value) {
  40630. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40631. this.addBehavior(this._autoRotationBehavior);
  40632. }
  40633. else if (this._autoRotationBehavior) {
  40634. this.removeBehavior(this._autoRotationBehavior);
  40635. this._autoRotationBehavior = null;
  40636. }
  40637. },
  40638. enumerable: true,
  40639. configurable: true
  40640. });
  40641. // Cache
  40642. ArcRotateCamera.prototype._initCache = function () {
  40643. _super.prototype._initCache.call(this);
  40644. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40645. this._cache.alpha = undefined;
  40646. this._cache.beta = undefined;
  40647. this._cache.radius = undefined;
  40648. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40649. };
  40650. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40651. if (!ignoreParentClass) {
  40652. _super.prototype._updateCache.call(this);
  40653. }
  40654. this._cache._target.copyFrom(this._getTargetPosition());
  40655. this._cache.alpha = this.alpha;
  40656. this._cache.beta = this.beta;
  40657. this._cache.radius = this.radius;
  40658. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40659. };
  40660. ArcRotateCamera.prototype._getTargetPosition = function () {
  40661. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40662. var pos = this._targetHost.getAbsolutePosition();
  40663. if (this._targetBoundingCenter) {
  40664. pos.addToRef(this._targetBoundingCenter, this._target);
  40665. }
  40666. else {
  40667. this._target.copyFrom(pos);
  40668. }
  40669. }
  40670. var lockedTargetPosition = this._getLockedTargetPosition();
  40671. if (lockedTargetPosition) {
  40672. return lockedTargetPosition;
  40673. }
  40674. return this._target;
  40675. };
  40676. ArcRotateCamera.prototype.storeState = function () {
  40677. this._storedAlpha = this.alpha;
  40678. this._storedBeta = this.beta;
  40679. this._storedRadius = this.radius;
  40680. this._storedTarget = this._getTargetPosition().clone();
  40681. return _super.prototype.storeState.call(this);
  40682. };
  40683. /**
  40684. * Restored camera state. You must call storeState() first
  40685. */
  40686. ArcRotateCamera.prototype._restoreStateValues = function () {
  40687. if (!_super.prototype._restoreStateValues.call(this)) {
  40688. return false;
  40689. }
  40690. this.alpha = this._storedAlpha;
  40691. this.beta = this._storedBeta;
  40692. this.radius = this._storedRadius;
  40693. this.setTarget(this._storedTarget.clone());
  40694. this.inertialAlphaOffset = 0;
  40695. this.inertialBetaOffset = 0;
  40696. this.inertialRadiusOffset = 0;
  40697. this.inertialPanningX = 0;
  40698. this.inertialPanningY = 0;
  40699. return true;
  40700. };
  40701. // Synchronized
  40702. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40703. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40704. return false;
  40705. return this._cache._target.equals(this._getTargetPosition())
  40706. && this._cache.alpha === this.alpha
  40707. && this._cache.beta === this.beta
  40708. && this._cache.radius === this.radius
  40709. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40710. };
  40711. // Methods
  40712. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40713. var _this = this;
  40714. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40715. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40716. this._useCtrlForPanning = useCtrlForPanning;
  40717. this._panningMouseButton = panningMouseButton;
  40718. this.inputs.attachElement(element, noPreventDefault);
  40719. this._reset = function () {
  40720. _this.inertialAlphaOffset = 0;
  40721. _this.inertialBetaOffset = 0;
  40722. _this.inertialRadiusOffset = 0;
  40723. _this.inertialPanningX = 0;
  40724. _this.inertialPanningY = 0;
  40725. };
  40726. };
  40727. ArcRotateCamera.prototype.detachControl = function (element) {
  40728. this.inputs.detachElement(element);
  40729. if (this._reset) {
  40730. this._reset();
  40731. }
  40732. };
  40733. ArcRotateCamera.prototype._checkInputs = function () {
  40734. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40735. if (this._collisionTriggered) {
  40736. return;
  40737. }
  40738. this.inputs.checkInputs();
  40739. // Inertia
  40740. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40741. if (this.getScene().useRightHandedSystem) {
  40742. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40743. }
  40744. else {
  40745. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40746. }
  40747. this.beta += this.inertialBetaOffset;
  40748. this.radius -= this.inertialRadiusOffset;
  40749. this.inertialAlphaOffset *= this.inertia;
  40750. this.inertialBetaOffset *= this.inertia;
  40751. this.inertialRadiusOffset *= this.inertia;
  40752. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40753. this.inertialAlphaOffset = 0;
  40754. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40755. this.inertialBetaOffset = 0;
  40756. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40757. this.inertialRadiusOffset = 0;
  40758. }
  40759. // Panning inertia
  40760. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40761. if (!this._localDirection) {
  40762. this._localDirection = BABYLON.Vector3.Zero();
  40763. this._transformedDirection = BABYLON.Vector3.Zero();
  40764. }
  40765. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40766. this._localDirection.multiplyInPlace(this.panningAxis);
  40767. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40768. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40769. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40770. if (!this.panningAxis.y) {
  40771. this._transformedDirection.y = 0;
  40772. }
  40773. if (!this._targetHost) {
  40774. if (this.panningDistanceLimit) {
  40775. this._transformedDirection.addInPlace(this._target);
  40776. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40777. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40778. this._target.copyFrom(this._transformedDirection);
  40779. }
  40780. }
  40781. else {
  40782. this._target.addInPlace(this._transformedDirection);
  40783. }
  40784. }
  40785. this.inertialPanningX *= this.panningInertia;
  40786. this.inertialPanningY *= this.panningInertia;
  40787. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40788. this.inertialPanningX = 0;
  40789. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40790. this.inertialPanningY = 0;
  40791. }
  40792. // Limits
  40793. this._checkLimits();
  40794. _super.prototype._checkInputs.call(this);
  40795. };
  40796. ArcRotateCamera.prototype._checkLimits = function () {
  40797. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40798. if (this.allowUpsideDown && this.beta > Math.PI) {
  40799. this.beta = this.beta - (2 * Math.PI);
  40800. }
  40801. }
  40802. else {
  40803. if (this.beta < this.lowerBetaLimit) {
  40804. this.beta = this.lowerBetaLimit;
  40805. }
  40806. }
  40807. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40808. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40809. this.beta = this.beta + (2 * Math.PI);
  40810. }
  40811. }
  40812. else {
  40813. if (this.beta > this.upperBetaLimit) {
  40814. this.beta = this.upperBetaLimit;
  40815. }
  40816. }
  40817. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40818. this.alpha = this.lowerAlphaLimit;
  40819. }
  40820. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40821. this.alpha = this.upperAlphaLimit;
  40822. }
  40823. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40824. this.radius = this.lowerRadiusLimit;
  40825. }
  40826. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40827. this.radius = this.upperRadiusLimit;
  40828. }
  40829. };
  40830. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40831. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40832. this.radius = radiusv3.length();
  40833. if (this.radius === 0) {
  40834. this.radius = 0.0001; // Just to avoid division by zero
  40835. }
  40836. // Alpha
  40837. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40838. if (radiusv3.z < 0) {
  40839. this.alpha = 2 * Math.PI - this.alpha;
  40840. }
  40841. // Beta
  40842. this.beta = Math.acos(radiusv3.y / this.radius);
  40843. this._checkLimits();
  40844. };
  40845. ArcRotateCamera.prototype.setPosition = function (position) {
  40846. if (this.position.equals(position)) {
  40847. return;
  40848. }
  40849. this.position.copyFrom(position);
  40850. this.rebuildAnglesAndRadius();
  40851. };
  40852. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40853. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40854. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40855. if (target.getBoundingInfo) {
  40856. if (toBoundingCenter) {
  40857. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40858. }
  40859. else {
  40860. this._targetBoundingCenter = null;
  40861. }
  40862. this._targetHost = target;
  40863. this._target = this._getTargetPosition();
  40864. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40865. }
  40866. else {
  40867. var newTarget = target;
  40868. var currentTarget = this._getTargetPosition();
  40869. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40870. return;
  40871. }
  40872. this._targetHost = null;
  40873. this._target = newTarget;
  40874. this._targetBoundingCenter = null;
  40875. this.onMeshTargetChangedObservable.notifyObservers(null);
  40876. }
  40877. this.rebuildAnglesAndRadius();
  40878. };
  40879. ArcRotateCamera.prototype._getViewMatrix = function () {
  40880. // Compute
  40881. var cosa = Math.cos(this.alpha);
  40882. var sina = Math.sin(this.alpha);
  40883. var cosb = Math.cos(this.beta);
  40884. var sinb = Math.sin(this.beta);
  40885. if (sinb === 0) {
  40886. sinb = 0.0001;
  40887. }
  40888. var target = this._getTargetPosition();
  40889. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40890. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40891. if (!this._collider) {
  40892. this._collider = new BABYLON.Collider();
  40893. }
  40894. this._collider._radius = this.collisionRadius;
  40895. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40896. this._collisionTriggered = true;
  40897. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40898. }
  40899. else {
  40900. this.position.copyFrom(this._newPosition);
  40901. var up = this.upVector;
  40902. if (this.allowUpsideDown && sinb < 0) {
  40903. up = up.clone();
  40904. up = up.negate();
  40905. }
  40906. if (this.getScene().useRightHandedSystem) {
  40907. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40908. }
  40909. else {
  40910. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40911. }
  40912. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40913. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40914. }
  40915. this._currentTarget = target;
  40916. return this._viewMatrix;
  40917. };
  40918. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40919. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40920. meshes = meshes || this.getScene().meshes;
  40921. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40922. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40923. this.radius = distance * this.zoomOnFactor;
  40924. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40925. };
  40926. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40927. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40928. var meshesOrMinMaxVector;
  40929. var distance;
  40930. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40931. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40932. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40933. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40934. }
  40935. else {
  40936. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40937. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40938. distance = minMaxVectorAndDistance.distance;
  40939. }
  40940. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40941. if (!doNotUpdateMaxZ) {
  40942. this.maxZ = distance * 2;
  40943. }
  40944. };
  40945. /**
  40946. * @override
  40947. * Override Camera.createRigCamera
  40948. */
  40949. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40950. var alphaShift = 0;
  40951. switch (this.cameraRigMode) {
  40952. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40953. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40954. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40955. case BABYLON.Camera.RIG_MODE_VR:
  40956. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40957. break;
  40958. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40959. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40960. break;
  40961. }
  40962. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40963. rigCam._cameraRigParams = {};
  40964. return rigCam;
  40965. };
  40966. /**
  40967. * @override
  40968. * Override Camera._updateRigCameras
  40969. */
  40970. ArcRotateCamera.prototype._updateRigCameras = function () {
  40971. var camLeft = this._rigCameras[0];
  40972. var camRight = this._rigCameras[1];
  40973. camLeft.beta = camRight.beta = this.beta;
  40974. camLeft.radius = camRight.radius = this.radius;
  40975. switch (this.cameraRigMode) {
  40976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40977. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40978. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40979. case BABYLON.Camera.RIG_MODE_VR:
  40980. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40981. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40982. break;
  40983. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40984. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40985. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40986. break;
  40987. }
  40988. _super.prototype._updateRigCameras.call(this);
  40989. };
  40990. ArcRotateCamera.prototype.dispose = function () {
  40991. this.inputs.clear();
  40992. _super.prototype.dispose.call(this);
  40993. };
  40994. ArcRotateCamera.prototype.getClassName = function () {
  40995. return "ArcRotateCamera";
  40996. };
  40997. __decorate([
  40998. BABYLON.serialize()
  40999. ], ArcRotateCamera.prototype, "alpha", void 0);
  41000. __decorate([
  41001. BABYLON.serialize()
  41002. ], ArcRotateCamera.prototype, "beta", void 0);
  41003. __decorate([
  41004. BABYLON.serialize()
  41005. ], ArcRotateCamera.prototype, "radius", void 0);
  41006. __decorate([
  41007. BABYLON.serializeAsVector3("target")
  41008. ], ArcRotateCamera.prototype, "_target", void 0);
  41009. __decorate([
  41010. BABYLON.serialize()
  41011. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41012. __decorate([
  41013. BABYLON.serialize()
  41014. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41015. __decorate([
  41016. BABYLON.serialize()
  41017. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41018. __decorate([
  41019. BABYLON.serialize()
  41020. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41021. __decorate([
  41022. BABYLON.serialize()
  41023. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41024. __decorate([
  41025. BABYLON.serialize()
  41026. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41027. __decorate([
  41028. BABYLON.serialize()
  41029. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41030. __decorate([
  41031. BABYLON.serialize()
  41032. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41033. __decorate([
  41034. BABYLON.serialize()
  41035. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41036. __decorate([
  41037. BABYLON.serialize()
  41038. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41039. __decorate([
  41040. BABYLON.serialize()
  41041. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41042. __decorate([
  41043. BABYLON.serialize()
  41044. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41045. __decorate([
  41046. BABYLON.serialize()
  41047. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41048. __decorate([
  41049. BABYLON.serializeAsVector3()
  41050. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41051. __decorate([
  41052. BABYLON.serialize()
  41053. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41054. __decorate([
  41055. BABYLON.serialize()
  41056. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41057. __decorate([
  41058. BABYLON.serialize()
  41059. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41060. return ArcRotateCamera;
  41061. }(BABYLON.TargetCamera));
  41062. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41063. })(BABYLON || (BABYLON = {}));
  41064. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41065. var BABYLON;
  41066. (function (BABYLON) {
  41067. var HemisphericLight = /** @class */ (function (_super) {
  41068. __extends(HemisphericLight, _super);
  41069. /**
  41070. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41071. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41072. * The HemisphericLight can't cast shadows.
  41073. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41074. */
  41075. function HemisphericLight(name, direction, scene) {
  41076. var _this = _super.call(this, name, scene) || this;
  41077. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41078. _this.direction = direction || BABYLON.Vector3.Up();
  41079. return _this;
  41080. }
  41081. HemisphericLight.prototype._buildUniformLayout = function () {
  41082. this._uniformBuffer.addUniform("vLightData", 4);
  41083. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41084. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41085. this._uniformBuffer.addUniform("vLightGround", 3);
  41086. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41087. this._uniformBuffer.addUniform("depthValues", 2);
  41088. this._uniformBuffer.create();
  41089. };
  41090. /**
  41091. * Returns the string "HemisphericLight".
  41092. */
  41093. HemisphericLight.prototype.getClassName = function () {
  41094. return "HemisphericLight";
  41095. };
  41096. /**
  41097. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41098. * Returns the updated direction.
  41099. */
  41100. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41101. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41102. return this.direction;
  41103. };
  41104. HemisphericLight.prototype.getShadowGenerator = function () {
  41105. return null;
  41106. };
  41107. /**
  41108. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41109. * Returns the HemisphericLight.
  41110. */
  41111. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41112. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41113. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41114. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41115. return this;
  41116. };
  41117. HemisphericLight.prototype._getWorldMatrix = function () {
  41118. if (!this._worldMatrix) {
  41119. this._worldMatrix = BABYLON.Matrix.Identity();
  41120. }
  41121. return this._worldMatrix;
  41122. };
  41123. /**
  41124. * Returns the integer 3.
  41125. */
  41126. HemisphericLight.prototype.getTypeID = function () {
  41127. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41128. };
  41129. __decorate([
  41130. BABYLON.serializeAsColor3()
  41131. ], HemisphericLight.prototype, "groundColor", void 0);
  41132. __decorate([
  41133. BABYLON.serializeAsVector3()
  41134. ], HemisphericLight.prototype, "direction", void 0);
  41135. return HemisphericLight;
  41136. }(BABYLON.Light));
  41137. BABYLON.HemisphericLight = HemisphericLight;
  41138. })(BABYLON || (BABYLON = {}));
  41139. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41140. var BABYLON;
  41141. (function (BABYLON) {
  41142. var ShadowLight = /** @class */ (function (_super) {
  41143. __extends(ShadowLight, _super);
  41144. function ShadowLight() {
  41145. var _this = _super !== null && _super.apply(this, arguments) || this;
  41146. _this._needProjectionMatrixCompute = true;
  41147. return _this;
  41148. }
  41149. Object.defineProperty(ShadowLight.prototype, "direction", {
  41150. get: function () {
  41151. return this._direction;
  41152. },
  41153. set: function (value) {
  41154. this._direction = value;
  41155. },
  41156. enumerable: true,
  41157. configurable: true
  41158. });
  41159. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41160. get: function () {
  41161. return this._shadowMinZ;
  41162. },
  41163. set: function (value) {
  41164. this._shadowMinZ = value;
  41165. this.forceProjectionMatrixCompute();
  41166. },
  41167. enumerable: true,
  41168. configurable: true
  41169. });
  41170. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41171. get: function () {
  41172. return this._shadowMaxZ;
  41173. },
  41174. set: function (value) {
  41175. this._shadowMaxZ = value;
  41176. this.forceProjectionMatrixCompute();
  41177. },
  41178. enumerable: true,
  41179. configurable: true
  41180. });
  41181. /**
  41182. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41183. */
  41184. ShadowLight.prototype.computeTransformedInformation = function () {
  41185. if (this.parent && this.parent.getWorldMatrix) {
  41186. if (!this.transformedPosition) {
  41187. this.transformedPosition = BABYLON.Vector3.Zero();
  41188. }
  41189. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41190. // In case the direction is present.
  41191. if (this.direction) {
  41192. if (!this.transformedDirection) {
  41193. this.transformedDirection = BABYLON.Vector3.Zero();
  41194. }
  41195. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41196. }
  41197. return true;
  41198. }
  41199. return false;
  41200. };
  41201. /**
  41202. * Return the depth scale used for the shadow map.
  41203. */
  41204. ShadowLight.prototype.getDepthScale = function () {
  41205. return 50.0;
  41206. };
  41207. /**
  41208. * Returns the light direction (Vector3) for any passed face index.
  41209. */
  41210. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41211. return this.transformedDirection ? this.transformedDirection : this.direction;
  41212. };
  41213. /**
  41214. * Returns the DirectionalLight absolute position in the World.
  41215. */
  41216. ShadowLight.prototype.getAbsolutePosition = function () {
  41217. return this.transformedPosition ? this.transformedPosition : this.position;
  41218. };
  41219. /**
  41220. * Sets the DirectionalLight direction toward the passed target (Vector3).
  41221. * Returns the updated DirectionalLight direction (Vector3).
  41222. */
  41223. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41224. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41225. return this.direction;
  41226. };
  41227. /**
  41228. * Returns the light rotation (Vector3).
  41229. */
  41230. ShadowLight.prototype.getRotation = function () {
  41231. this.direction.normalize();
  41232. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41233. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41234. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41235. };
  41236. /**
  41237. * Boolean : false by default.
  41238. */
  41239. ShadowLight.prototype.needCube = function () {
  41240. return false;
  41241. };
  41242. /**
  41243. * Specifies wether or not the projection matrix should be recomputed this frame.
  41244. */
  41245. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41246. return this._needProjectionMatrixCompute;
  41247. };
  41248. /**
  41249. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41250. */
  41251. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41252. this._needProjectionMatrixCompute = true;
  41253. };
  41254. /**
  41255. * Get the world matrix of the sahdow lights.
  41256. */
  41257. ShadowLight.prototype._getWorldMatrix = function () {
  41258. if (!this._worldMatrix) {
  41259. this._worldMatrix = BABYLON.Matrix.Identity();
  41260. }
  41261. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41262. return this._worldMatrix;
  41263. };
  41264. /**
  41265. * Gets the minZ used for shadow according to both the scene and the light.
  41266. * @param activeCamera
  41267. */
  41268. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41269. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41270. };
  41271. /**
  41272. * Gets the maxZ used for shadow according to both the scene and the light.
  41273. * @param activeCamera
  41274. */
  41275. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41276. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41277. };
  41278. /**
  41279. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41280. * Returns the light.
  41281. */
  41282. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41283. if (this.customProjectionMatrixBuilder) {
  41284. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41285. }
  41286. else {
  41287. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41288. }
  41289. return this;
  41290. };
  41291. __decorate([
  41292. BABYLON.serializeAsVector3()
  41293. ], ShadowLight.prototype, "position", void 0);
  41294. __decorate([
  41295. BABYLON.serializeAsVector3()
  41296. ], ShadowLight.prototype, "direction", null);
  41297. __decorate([
  41298. BABYLON.serialize()
  41299. ], ShadowLight.prototype, "shadowMinZ", null);
  41300. __decorate([
  41301. BABYLON.serialize()
  41302. ], ShadowLight.prototype, "shadowMaxZ", null);
  41303. return ShadowLight;
  41304. }(BABYLON.Light));
  41305. BABYLON.ShadowLight = ShadowLight;
  41306. })(BABYLON || (BABYLON = {}));
  41307. //# sourceMappingURL=babylon.shadowLight.js.map
  41308. var BABYLON;
  41309. (function (BABYLON) {
  41310. var PointLight = /** @class */ (function (_super) {
  41311. __extends(PointLight, _super);
  41312. /**
  41313. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41314. * A PointLight emits the light in every direction.
  41315. * It can cast shadows.
  41316. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41317. * ```javascript
  41318. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41319. * ```
  41320. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41321. */
  41322. function PointLight(name, position, scene) {
  41323. var _this = _super.call(this, name, scene) || this;
  41324. _this._shadowAngle = Math.PI / 2;
  41325. _this.position = position;
  41326. return _this;
  41327. }
  41328. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41329. /**
  41330. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41331. * This specifies what angle the shadow will use to be created.
  41332. *
  41333. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41334. */
  41335. get: function () {
  41336. return this._shadowAngle;
  41337. },
  41338. /**
  41339. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41340. * This specifies what angle the shadow will use to be created.
  41341. *
  41342. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41343. */
  41344. set: function (value) {
  41345. this._shadowAngle = value;
  41346. this.forceProjectionMatrixCompute();
  41347. },
  41348. enumerable: true,
  41349. configurable: true
  41350. });
  41351. Object.defineProperty(PointLight.prototype, "direction", {
  41352. get: function () {
  41353. return this._direction;
  41354. },
  41355. /**
  41356. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41357. */
  41358. set: function (value) {
  41359. var previousNeedCube = this.needCube();
  41360. this._direction = value;
  41361. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41362. this._shadowGenerator.recreateShadowMap();
  41363. }
  41364. },
  41365. enumerable: true,
  41366. configurable: true
  41367. });
  41368. /**
  41369. * Returns the string "PointLight"
  41370. */
  41371. PointLight.prototype.getClassName = function () {
  41372. return "PointLight";
  41373. };
  41374. /**
  41375. * Returns the integer 0.
  41376. */
  41377. PointLight.prototype.getTypeID = function () {
  41378. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41379. };
  41380. /**
  41381. * Specifies wether or not the shadowmap should be a cube texture.
  41382. */
  41383. PointLight.prototype.needCube = function () {
  41384. return !this.direction;
  41385. };
  41386. /**
  41387. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41388. */
  41389. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41390. if (this.direction) {
  41391. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41392. }
  41393. else {
  41394. switch (faceIndex) {
  41395. case 0:
  41396. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41397. case 1:
  41398. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41399. case 2:
  41400. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41401. case 3:
  41402. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41403. case 4:
  41404. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41405. case 5:
  41406. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41407. }
  41408. }
  41409. return BABYLON.Vector3.Zero();
  41410. };
  41411. /**
  41412. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41413. * - fov = PI / 2
  41414. * - aspect ratio : 1.0
  41415. * - z-near and far equal to the active camera minZ and maxZ.
  41416. * Returns the PointLight.
  41417. */
  41418. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41419. var activeCamera = this.getScene().activeCamera;
  41420. if (!activeCamera) {
  41421. return;
  41422. }
  41423. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41424. };
  41425. PointLight.prototype._buildUniformLayout = function () {
  41426. this._uniformBuffer.addUniform("vLightData", 4);
  41427. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41428. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41429. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41430. this._uniformBuffer.addUniform("depthValues", 2);
  41431. this._uniformBuffer.create();
  41432. };
  41433. /**
  41434. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41435. * Returns the PointLight.
  41436. */
  41437. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41438. if (this.computeTransformedInformation()) {
  41439. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41440. return this;
  41441. }
  41442. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41443. return this;
  41444. };
  41445. __decorate([
  41446. BABYLON.serialize()
  41447. ], PointLight.prototype, "shadowAngle", null);
  41448. return PointLight;
  41449. }(BABYLON.ShadowLight));
  41450. BABYLON.PointLight = PointLight;
  41451. })(BABYLON || (BABYLON = {}));
  41452. //# sourceMappingURL=babylon.pointLight.js.map
  41453. var BABYLON;
  41454. (function (BABYLON) {
  41455. var DirectionalLight = /** @class */ (function (_super) {
  41456. __extends(DirectionalLight, _super);
  41457. /**
  41458. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41459. * The directional light is emitted from everywhere in the given direction.
  41460. * It can cast shawdows.
  41461. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41462. */
  41463. function DirectionalLight(name, direction, scene) {
  41464. var _this = _super.call(this, name, scene) || this;
  41465. _this._shadowFrustumSize = 0;
  41466. _this._shadowOrthoScale = 0.5;
  41467. _this.autoUpdateExtends = true;
  41468. // Cache
  41469. _this._orthoLeft = Number.MAX_VALUE;
  41470. _this._orthoRight = Number.MIN_VALUE;
  41471. _this._orthoTop = Number.MIN_VALUE;
  41472. _this._orthoBottom = Number.MAX_VALUE;
  41473. _this.position = direction.scale(-1.0);
  41474. _this.direction = direction;
  41475. return _this;
  41476. }
  41477. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41478. /**
  41479. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41480. */
  41481. get: function () {
  41482. return this._shadowFrustumSize;
  41483. },
  41484. /**
  41485. * Specifies a fix frustum size for the shadow generation.
  41486. */
  41487. set: function (value) {
  41488. this._shadowFrustumSize = value;
  41489. this.forceProjectionMatrixCompute();
  41490. },
  41491. enumerable: true,
  41492. configurable: true
  41493. });
  41494. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41495. get: function () {
  41496. return this._shadowOrthoScale;
  41497. },
  41498. set: function (value) {
  41499. this._shadowOrthoScale = value;
  41500. this.forceProjectionMatrixCompute();
  41501. },
  41502. enumerable: true,
  41503. configurable: true
  41504. });
  41505. /**
  41506. * Returns the string "DirectionalLight".
  41507. */
  41508. DirectionalLight.prototype.getClassName = function () {
  41509. return "DirectionalLight";
  41510. };
  41511. /**
  41512. * Returns the integer 1.
  41513. */
  41514. DirectionalLight.prototype.getTypeID = function () {
  41515. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41516. };
  41517. /**
  41518. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41519. * Returns the DirectionalLight Shadow projection matrix.
  41520. */
  41521. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41522. if (this.shadowFrustumSize > 0) {
  41523. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41524. }
  41525. else {
  41526. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41527. }
  41528. };
  41529. /**
  41530. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41531. * Returns the DirectionalLight Shadow projection matrix.
  41532. */
  41533. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41534. var activeCamera = this.getScene().activeCamera;
  41535. if (!activeCamera) {
  41536. return;
  41537. }
  41538. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41539. };
  41540. /**
  41541. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41542. * Returns the DirectionalLight Shadow projection matrix.
  41543. */
  41544. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41545. var activeCamera = this.getScene().activeCamera;
  41546. if (!activeCamera) {
  41547. return;
  41548. }
  41549. // Check extends
  41550. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41551. var tempVector3 = BABYLON.Vector3.Zero();
  41552. this._orthoLeft = Number.MAX_VALUE;
  41553. this._orthoRight = Number.MIN_VALUE;
  41554. this._orthoTop = Number.MIN_VALUE;
  41555. this._orthoBottom = Number.MAX_VALUE;
  41556. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41557. var mesh = renderList[meshIndex];
  41558. if (!mesh) {
  41559. continue;
  41560. }
  41561. var boundingInfo = mesh.getBoundingInfo();
  41562. var boundingBox = boundingInfo.boundingBox;
  41563. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41564. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41565. if (tempVector3.x < this._orthoLeft)
  41566. this._orthoLeft = tempVector3.x;
  41567. if (tempVector3.y < this._orthoBottom)
  41568. this._orthoBottom = tempVector3.y;
  41569. if (tempVector3.x > this._orthoRight)
  41570. this._orthoRight = tempVector3.x;
  41571. if (tempVector3.y > this._orthoTop)
  41572. this._orthoTop = tempVector3.y;
  41573. }
  41574. }
  41575. }
  41576. var xOffset = this._orthoRight - this._orthoLeft;
  41577. var yOffset = this._orthoTop - this._orthoBottom;
  41578. 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);
  41579. };
  41580. DirectionalLight.prototype._buildUniformLayout = function () {
  41581. this._uniformBuffer.addUniform("vLightData", 4);
  41582. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41583. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41584. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41585. this._uniformBuffer.addUniform("depthValues", 2);
  41586. this._uniformBuffer.create();
  41587. };
  41588. /**
  41589. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41590. * Returns the DirectionalLight.
  41591. */
  41592. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41593. if (this.computeTransformedInformation()) {
  41594. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41595. return this;
  41596. }
  41597. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41598. return this;
  41599. };
  41600. /**
  41601. * Gets the minZ used for shadow according to both the scene and the light.
  41602. *
  41603. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41604. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41605. * @param activeCamera
  41606. */
  41607. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41608. return 1;
  41609. };
  41610. /**
  41611. * Gets the maxZ used for shadow according to both the scene and the light.
  41612. *
  41613. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41614. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41615. * @param activeCamera
  41616. */
  41617. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41618. return 1;
  41619. };
  41620. __decorate([
  41621. BABYLON.serialize()
  41622. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41623. __decorate([
  41624. BABYLON.serialize()
  41625. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41626. __decorate([
  41627. BABYLON.serialize()
  41628. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41629. return DirectionalLight;
  41630. }(BABYLON.ShadowLight));
  41631. BABYLON.DirectionalLight = DirectionalLight;
  41632. })(BABYLON || (BABYLON = {}));
  41633. //# sourceMappingURL=babylon.directionalLight.js.map
  41634. var BABYLON;
  41635. (function (BABYLON) {
  41636. var SpotLight = /** @class */ (function (_super) {
  41637. __extends(SpotLight, _super);
  41638. /**
  41639. * Creates a SpotLight object in the scene with the passed parameters :
  41640. * - `position` (Vector3) is the initial SpotLight position,
  41641. * - `direction` (Vector3) is the initial SpotLight direction,
  41642. * - `angle` (float, in radians) is the spot light cone angle,
  41643. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41644. * A spot light is a simply light oriented cone.
  41645. * It can cast shadows.
  41646. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41647. */
  41648. function SpotLight(name, position, direction, angle, exponent, scene) {
  41649. var _this = _super.call(this, name, scene) || this;
  41650. _this.position = position;
  41651. _this.direction = direction;
  41652. _this.angle = angle;
  41653. _this.exponent = exponent;
  41654. return _this;
  41655. }
  41656. Object.defineProperty(SpotLight.prototype, "angle", {
  41657. get: function () {
  41658. return this._angle;
  41659. },
  41660. set: function (value) {
  41661. this._angle = value;
  41662. this.forceProjectionMatrixCompute();
  41663. },
  41664. enumerable: true,
  41665. configurable: true
  41666. });
  41667. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41668. get: function () {
  41669. return this._shadowAngleScale;
  41670. },
  41671. /**
  41672. * Allows scaling the angle of the light for shadow generation only.
  41673. */
  41674. set: function (value) {
  41675. this._shadowAngleScale = value;
  41676. this.forceProjectionMatrixCompute();
  41677. },
  41678. enumerable: true,
  41679. configurable: true
  41680. });
  41681. /**
  41682. * Returns the string "SpotLight".
  41683. */
  41684. SpotLight.prototype.getClassName = function () {
  41685. return "SpotLight";
  41686. };
  41687. /**
  41688. * Returns the integer 2.
  41689. */
  41690. SpotLight.prototype.getTypeID = function () {
  41691. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41692. };
  41693. /**
  41694. * 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.
  41695. * Returns the SpotLight.
  41696. */
  41697. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41698. var activeCamera = this.getScene().activeCamera;
  41699. if (!activeCamera) {
  41700. return;
  41701. }
  41702. this._shadowAngleScale = this._shadowAngleScale || 1;
  41703. var angle = this._shadowAngleScale * this._angle;
  41704. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41705. };
  41706. SpotLight.prototype._buildUniformLayout = function () {
  41707. this._uniformBuffer.addUniform("vLightData", 4);
  41708. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41709. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41710. this._uniformBuffer.addUniform("vLightDirection", 3);
  41711. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41712. this._uniformBuffer.addUniform("depthValues", 2);
  41713. this._uniformBuffer.create();
  41714. };
  41715. /**
  41716. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41717. * Return the SpotLight.
  41718. */
  41719. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41720. var normalizeDirection;
  41721. if (this.computeTransformedInformation()) {
  41722. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41723. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41724. }
  41725. else {
  41726. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41727. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41728. }
  41729. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41730. return this;
  41731. };
  41732. __decorate([
  41733. BABYLON.serialize()
  41734. ], SpotLight.prototype, "angle", null);
  41735. __decorate([
  41736. BABYLON.serialize()
  41737. /**
  41738. * Allows scaling the angle of the light for shadow generation only.
  41739. */
  41740. ], SpotLight.prototype, "shadowAngleScale", null);
  41741. __decorate([
  41742. BABYLON.serialize()
  41743. ], SpotLight.prototype, "exponent", void 0);
  41744. return SpotLight;
  41745. }(BABYLON.ShadowLight));
  41746. BABYLON.SpotLight = SpotLight;
  41747. })(BABYLON || (BABYLON = {}));
  41748. //# sourceMappingURL=babylon.spotLight.js.map
  41749. var BABYLON;
  41750. (function (BABYLON) {
  41751. var AnimationRange = /** @class */ (function () {
  41752. function AnimationRange(name, from, to) {
  41753. this.name = name;
  41754. this.from = from;
  41755. this.to = to;
  41756. }
  41757. AnimationRange.prototype.clone = function () {
  41758. return new AnimationRange(this.name, this.from, this.to);
  41759. };
  41760. return AnimationRange;
  41761. }());
  41762. BABYLON.AnimationRange = AnimationRange;
  41763. /**
  41764. * Composed of a frame, and an action function
  41765. */
  41766. var AnimationEvent = /** @class */ (function () {
  41767. function AnimationEvent(frame, action, onlyOnce) {
  41768. this.frame = frame;
  41769. this.action = action;
  41770. this.onlyOnce = onlyOnce;
  41771. this.isDone = false;
  41772. }
  41773. return AnimationEvent;
  41774. }());
  41775. BABYLON.AnimationEvent = AnimationEvent;
  41776. var PathCursor = /** @class */ (function () {
  41777. function PathCursor(path) {
  41778. this.path = path;
  41779. this._onchange = new Array();
  41780. this.value = 0;
  41781. this.animations = new Array();
  41782. }
  41783. PathCursor.prototype.getPoint = function () {
  41784. var point = this.path.getPointAtLengthPosition(this.value);
  41785. return new BABYLON.Vector3(point.x, 0, point.y);
  41786. };
  41787. PathCursor.prototype.moveAhead = function (step) {
  41788. if (step === void 0) { step = 0.002; }
  41789. this.move(step);
  41790. return this;
  41791. };
  41792. PathCursor.prototype.moveBack = function (step) {
  41793. if (step === void 0) { step = 0.002; }
  41794. this.move(-step);
  41795. return this;
  41796. };
  41797. PathCursor.prototype.move = function (step) {
  41798. if (Math.abs(step) > 1) {
  41799. throw "step size should be less than 1.";
  41800. }
  41801. this.value += step;
  41802. this.ensureLimits();
  41803. this.raiseOnChange();
  41804. return this;
  41805. };
  41806. PathCursor.prototype.ensureLimits = function () {
  41807. while (this.value > 1) {
  41808. this.value -= 1;
  41809. }
  41810. while (this.value < 0) {
  41811. this.value += 1;
  41812. }
  41813. return this;
  41814. };
  41815. // used by animation engine
  41816. PathCursor.prototype.raiseOnChange = function () {
  41817. var _this = this;
  41818. this._onchange.forEach(function (f) { return f(_this); });
  41819. return this;
  41820. };
  41821. PathCursor.prototype.onchange = function (f) {
  41822. this._onchange.push(f);
  41823. return this;
  41824. };
  41825. return PathCursor;
  41826. }());
  41827. BABYLON.PathCursor = PathCursor;
  41828. var AnimationKeyInterpolation;
  41829. (function (AnimationKeyInterpolation) {
  41830. /**
  41831. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41832. */
  41833. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41834. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41835. var Animation = /** @class */ (function () {
  41836. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41837. this.name = name;
  41838. this.targetProperty = targetProperty;
  41839. this.framePerSecond = framePerSecond;
  41840. this.dataType = dataType;
  41841. this.loopMode = loopMode;
  41842. this.enableBlending = enableBlending;
  41843. this._runtimeAnimations = new Array();
  41844. // The set of event that will be linked to this animation
  41845. this._events = new Array();
  41846. this.blendingSpeed = 0.01;
  41847. this._ranges = {};
  41848. this.targetPropertyPath = targetProperty.split(".");
  41849. this.dataType = dataType;
  41850. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41851. }
  41852. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41853. var dataType = undefined;
  41854. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41855. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41856. }
  41857. else if (from instanceof BABYLON.Quaternion) {
  41858. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41859. }
  41860. else if (from instanceof BABYLON.Vector3) {
  41861. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41862. }
  41863. else if (from instanceof BABYLON.Vector2) {
  41864. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41865. }
  41866. else if (from instanceof BABYLON.Color3) {
  41867. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41868. }
  41869. else if (from instanceof BABYLON.Size) {
  41870. dataType = Animation.ANIMATIONTYPE_SIZE;
  41871. }
  41872. if (dataType == undefined) {
  41873. return null;
  41874. }
  41875. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41876. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41877. animation.setKeys(keys);
  41878. if (easingFunction !== undefined) {
  41879. animation.setEasingFunction(easingFunction);
  41880. }
  41881. return animation;
  41882. };
  41883. /**
  41884. * Sets up an animation.
  41885. * @param property the property to animate
  41886. * @param animationType the animation type to apply
  41887. * @param easingFunction the easing function used in the animation
  41888. * @returns The created animation
  41889. */
  41890. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41891. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41892. animation.setEasingFunction(easingFunction);
  41893. return animation;
  41894. };
  41895. /**
  41896. * Create and start an animation on a node
  41897. * @param {string} name defines the name of the global animation that will be run on all nodes
  41898. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41899. * @param {string} targetProperty defines property to animate
  41900. * @param {number} framePerSecond defines the number of frame per second yo use
  41901. * @param {number} totalFrame defines the number of frames in total
  41902. * @param {any} from defines the initial value
  41903. * @param {any} to defines the final value
  41904. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41905. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41906. * @param onAnimationEnd defines the callback to call when animation end
  41907. * @returns the animatable created for this animation
  41908. */
  41909. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41910. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41911. if (!animation) {
  41912. return null;
  41913. }
  41914. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41915. };
  41916. /**
  41917. * Create and start an animation on a node and its descendants
  41918. * @param {string} name defines the name of the global animation that will be run on all nodes
  41919. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41920. * @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.
  41921. * @param {string} targetProperty defines property to animate
  41922. * @param {number} framePerSecond defines the number of frame per second yo use
  41923. * @param {number} totalFrame defines the number of frames in total
  41924. * @param {any} from defines the initial value
  41925. * @param {any} to defines the final value
  41926. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41927. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41928. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41929. * @returns the list of animatables created for all nodes
  41930. * @example https://www.babylonjs-playground.com/#MH0VLI
  41931. */
  41932. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41933. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41934. if (!animation) {
  41935. return null;
  41936. }
  41937. var scene = node.getScene();
  41938. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41939. };
  41940. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41941. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41942. if (!animation) {
  41943. return null;
  41944. }
  41945. node.animations.push(animation);
  41946. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41947. };
  41948. /**
  41949. * Transition property of the Camera to the target Value.
  41950. * @param property The property to transition
  41951. * @param targetValue The target Value of the property
  41952. * @param host The object where the property to animate belongs
  41953. * @param scene Scene used to run the animation
  41954. * @param frameRate Framerate (in frame/s) to use
  41955. * @param transition The transition type we want to use
  41956. * @param duration The duration of the animation, in milliseconds
  41957. * @param onAnimationEnd Call back trigger at the end of the animation.
  41958. */
  41959. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41960. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41961. if (duration <= 0) {
  41962. host[property] = targetValue;
  41963. if (onAnimationEnd) {
  41964. onAnimationEnd();
  41965. }
  41966. return null;
  41967. }
  41968. var endFrame = frameRate * (duration / 1000);
  41969. transition.setKeys([{
  41970. frame: 0,
  41971. value: host[property].clone ? host[property].clone() : host[property]
  41972. },
  41973. {
  41974. frame: endFrame,
  41975. value: targetValue
  41976. }]);
  41977. if (!host.animations) {
  41978. host.animations = [];
  41979. }
  41980. host.animations.push(transition);
  41981. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41982. animation.onAnimationEnd = onAnimationEnd;
  41983. return animation;
  41984. };
  41985. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41986. /**
  41987. * Return the array of runtime animations currently using this animation
  41988. */
  41989. get: function () {
  41990. return this._runtimeAnimations;
  41991. },
  41992. enumerable: true,
  41993. configurable: true
  41994. });
  41995. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41996. get: function () {
  41997. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41998. var runtimeAnimation = _a[_i];
  41999. if (!runtimeAnimation.isStopped) {
  42000. return true;
  42001. }
  42002. }
  42003. return false;
  42004. },
  42005. enumerable: true,
  42006. configurable: true
  42007. });
  42008. // Methods
  42009. /**
  42010. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42011. */
  42012. Animation.prototype.toString = function (fullDetails) {
  42013. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42014. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42015. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42016. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42017. if (fullDetails) {
  42018. ret += ", Ranges: {";
  42019. var first = true;
  42020. for (var name in this._ranges) {
  42021. if (first) {
  42022. ret += ", ";
  42023. first = false;
  42024. }
  42025. ret += name;
  42026. }
  42027. ret += "}";
  42028. }
  42029. return ret;
  42030. };
  42031. /**
  42032. * Add an event to this animation.
  42033. */
  42034. Animation.prototype.addEvent = function (event) {
  42035. this._events.push(event);
  42036. };
  42037. /**
  42038. * Remove all events found at the given frame
  42039. * @param frame
  42040. */
  42041. Animation.prototype.removeEvents = function (frame) {
  42042. for (var index = 0; index < this._events.length; index++) {
  42043. if (this._events[index].frame === frame) {
  42044. this._events.splice(index, 1);
  42045. index--;
  42046. }
  42047. }
  42048. };
  42049. Animation.prototype.getEvents = function () {
  42050. return this._events;
  42051. };
  42052. Animation.prototype.createRange = function (name, from, to) {
  42053. // check name not already in use; could happen for bones after serialized
  42054. if (!this._ranges[name]) {
  42055. this._ranges[name] = new AnimationRange(name, from, to);
  42056. }
  42057. };
  42058. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42059. if (deleteFrames === void 0) { deleteFrames = true; }
  42060. var range = this._ranges[name];
  42061. if (!range) {
  42062. return;
  42063. }
  42064. if (deleteFrames) {
  42065. var from = range.from;
  42066. var to = range.to;
  42067. // this loop MUST go high to low for multiple splices to work
  42068. for (var key = this._keys.length - 1; key >= 0; key--) {
  42069. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42070. this._keys.splice(key, 1);
  42071. }
  42072. }
  42073. }
  42074. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42075. };
  42076. Animation.prototype.getRange = function (name) {
  42077. return this._ranges[name];
  42078. };
  42079. Animation.prototype.getKeys = function () {
  42080. return this._keys;
  42081. };
  42082. Animation.prototype.getHighestFrame = function () {
  42083. var ret = 0;
  42084. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42085. if (ret < this._keys[key].frame) {
  42086. ret = this._keys[key].frame;
  42087. }
  42088. }
  42089. return ret;
  42090. };
  42091. Animation.prototype.getEasingFunction = function () {
  42092. return this._easingFunction;
  42093. };
  42094. Animation.prototype.setEasingFunction = function (easingFunction) {
  42095. this._easingFunction = easingFunction;
  42096. };
  42097. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42098. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42099. };
  42100. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42101. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42102. };
  42103. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42104. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42105. };
  42106. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42107. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42108. };
  42109. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42110. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42111. };
  42112. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42113. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42114. };
  42115. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42116. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42117. };
  42118. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42119. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42120. };
  42121. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42122. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42123. };
  42124. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42125. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42126. };
  42127. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42128. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42129. };
  42130. Animation.prototype.clone = function () {
  42131. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42132. clone.enableBlending = this.enableBlending;
  42133. clone.blendingSpeed = this.blendingSpeed;
  42134. if (this._keys) {
  42135. clone.setKeys(this._keys);
  42136. }
  42137. if (this._ranges) {
  42138. clone._ranges = {};
  42139. for (var name in this._ranges) {
  42140. var range = this._ranges[name];
  42141. if (!range) {
  42142. continue;
  42143. }
  42144. clone._ranges[name] = range.clone();
  42145. }
  42146. }
  42147. return clone;
  42148. };
  42149. Animation.prototype.setKeys = function (values) {
  42150. this._keys = values.slice(0);
  42151. };
  42152. Animation.prototype.serialize = function () {
  42153. var serializationObject = {};
  42154. serializationObject.name = this.name;
  42155. serializationObject.property = this.targetProperty;
  42156. serializationObject.framePerSecond = this.framePerSecond;
  42157. serializationObject.dataType = this.dataType;
  42158. serializationObject.loopBehavior = this.loopMode;
  42159. serializationObject.enableBlending = this.enableBlending;
  42160. serializationObject.blendingSpeed = this.blendingSpeed;
  42161. var dataType = this.dataType;
  42162. serializationObject.keys = [];
  42163. var keys = this.getKeys();
  42164. for (var index = 0; index < keys.length; index++) {
  42165. var animationKey = keys[index];
  42166. var key = {};
  42167. key.frame = animationKey.frame;
  42168. switch (dataType) {
  42169. case Animation.ANIMATIONTYPE_FLOAT:
  42170. key.values = [animationKey.value];
  42171. break;
  42172. case Animation.ANIMATIONTYPE_QUATERNION:
  42173. case Animation.ANIMATIONTYPE_MATRIX:
  42174. case Animation.ANIMATIONTYPE_VECTOR3:
  42175. case Animation.ANIMATIONTYPE_COLOR3:
  42176. key.values = animationKey.value.asArray();
  42177. break;
  42178. }
  42179. serializationObject.keys.push(key);
  42180. }
  42181. serializationObject.ranges = [];
  42182. for (var name in this._ranges) {
  42183. var source = this._ranges[name];
  42184. if (!source) {
  42185. continue;
  42186. }
  42187. var range = {};
  42188. range.name = name;
  42189. range.from = source.from;
  42190. range.to = source.to;
  42191. serializationObject.ranges.push(range);
  42192. }
  42193. return serializationObject;
  42194. };
  42195. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42196. get: function () {
  42197. return Animation._ANIMATIONTYPE_FLOAT;
  42198. },
  42199. enumerable: true,
  42200. configurable: true
  42201. });
  42202. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42203. get: function () {
  42204. return Animation._ANIMATIONTYPE_VECTOR3;
  42205. },
  42206. enumerable: true,
  42207. configurable: true
  42208. });
  42209. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42210. get: function () {
  42211. return Animation._ANIMATIONTYPE_VECTOR2;
  42212. },
  42213. enumerable: true,
  42214. configurable: true
  42215. });
  42216. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42217. get: function () {
  42218. return Animation._ANIMATIONTYPE_SIZE;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42224. get: function () {
  42225. return Animation._ANIMATIONTYPE_QUATERNION;
  42226. },
  42227. enumerable: true,
  42228. configurable: true
  42229. });
  42230. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42231. get: function () {
  42232. return Animation._ANIMATIONTYPE_MATRIX;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42238. get: function () {
  42239. return Animation._ANIMATIONTYPE_COLOR3;
  42240. },
  42241. enumerable: true,
  42242. configurable: true
  42243. });
  42244. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42245. get: function () {
  42246. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42247. },
  42248. enumerable: true,
  42249. configurable: true
  42250. });
  42251. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42252. get: function () {
  42253. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42254. },
  42255. enumerable: true,
  42256. configurable: true
  42257. });
  42258. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42259. get: function () {
  42260. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. Animation.Parse = function (parsedAnimation) {
  42266. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42267. var dataType = parsedAnimation.dataType;
  42268. var keys = [];
  42269. var data;
  42270. var index;
  42271. if (parsedAnimation.enableBlending) {
  42272. animation.enableBlending = parsedAnimation.enableBlending;
  42273. }
  42274. if (parsedAnimation.blendingSpeed) {
  42275. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42276. }
  42277. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42278. var key = parsedAnimation.keys[index];
  42279. var inTangent;
  42280. var outTangent;
  42281. switch (dataType) {
  42282. case Animation.ANIMATIONTYPE_FLOAT:
  42283. data = key.values[0];
  42284. if (key.values.length >= 1) {
  42285. inTangent = key.values[1];
  42286. }
  42287. if (key.values.length >= 2) {
  42288. outTangent = key.values[2];
  42289. }
  42290. break;
  42291. case Animation.ANIMATIONTYPE_QUATERNION:
  42292. data = BABYLON.Quaternion.FromArray(key.values);
  42293. if (key.values.length >= 8) {
  42294. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42295. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42296. inTangent = _inTangent;
  42297. }
  42298. }
  42299. if (key.values.length >= 12) {
  42300. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42301. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42302. outTangent = _outTangent;
  42303. }
  42304. }
  42305. break;
  42306. case Animation.ANIMATIONTYPE_MATRIX:
  42307. data = BABYLON.Matrix.FromArray(key.values);
  42308. break;
  42309. case Animation.ANIMATIONTYPE_COLOR3:
  42310. data = BABYLON.Color3.FromArray(key.values);
  42311. break;
  42312. case Animation.ANIMATIONTYPE_VECTOR3:
  42313. default:
  42314. data = BABYLON.Vector3.FromArray(key.values);
  42315. break;
  42316. }
  42317. var keyData = {};
  42318. keyData.frame = key.frame;
  42319. keyData.value = data;
  42320. if (inTangent != undefined) {
  42321. keyData.inTangent = inTangent;
  42322. }
  42323. if (outTangent != undefined) {
  42324. keyData.outTangent = outTangent;
  42325. }
  42326. keys.push(keyData);
  42327. }
  42328. animation.setKeys(keys);
  42329. if (parsedAnimation.ranges) {
  42330. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42331. data = parsedAnimation.ranges[index];
  42332. animation.createRange(data.name, data.from, data.to);
  42333. }
  42334. }
  42335. return animation;
  42336. };
  42337. Animation.AppendSerializedAnimations = function (source, destination) {
  42338. if (source.animations) {
  42339. destination.animations = [];
  42340. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42341. var animation = source.animations[animationIndex];
  42342. destination.animations.push(animation.serialize());
  42343. }
  42344. }
  42345. };
  42346. Animation.AllowMatricesInterpolation = false;
  42347. // Statics
  42348. Animation._ANIMATIONTYPE_FLOAT = 0;
  42349. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42350. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42351. Animation._ANIMATIONTYPE_MATRIX = 3;
  42352. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42353. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42354. Animation._ANIMATIONTYPE_SIZE = 6;
  42355. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42356. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42357. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42358. return Animation;
  42359. }());
  42360. BABYLON.Animation = Animation;
  42361. })(BABYLON || (BABYLON = {}));
  42362. //# sourceMappingURL=babylon.animation.js.map
  42363. var BABYLON;
  42364. (function (BABYLON) {
  42365. /**
  42366. * This class defines the direct association between an animation and a target
  42367. */
  42368. var TargetedAnimation = /** @class */ (function () {
  42369. function TargetedAnimation() {
  42370. }
  42371. return TargetedAnimation;
  42372. }());
  42373. BABYLON.TargetedAnimation = TargetedAnimation;
  42374. /**
  42375. * Use this class to create coordinated animations on multiple targets
  42376. */
  42377. var AnimationGroup = /** @class */ (function () {
  42378. function AnimationGroup(name, scene) {
  42379. if (scene === void 0) { scene = null; }
  42380. this.name = name;
  42381. this._targetedAnimations = new Array();
  42382. this._animatables = new Array();
  42383. this._from = Number.MAX_VALUE;
  42384. this._to = Number.MIN_VALUE;
  42385. this._speedRatio = 1;
  42386. this.onAnimationEndObservable = new BABYLON.Observable();
  42387. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42388. this._scene.animationGroups.push(this);
  42389. }
  42390. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42391. /**
  42392. * Define if the animations are started
  42393. */
  42394. get: function () {
  42395. return this._isStarted;
  42396. },
  42397. enumerable: true,
  42398. configurable: true
  42399. });
  42400. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42401. /**
  42402. * Gets or sets the speed ratio to use for all animations
  42403. */
  42404. get: function () {
  42405. return this._speedRatio;
  42406. },
  42407. /**
  42408. * Gets or sets the speed ratio to use for all animations
  42409. */
  42410. set: function (value) {
  42411. if (this._speedRatio === value) {
  42412. return;
  42413. }
  42414. this._speedRatio = value;
  42415. for (var index = 0; index < this._animatables.length; index++) {
  42416. var animatable = this._animatables[index];
  42417. animatable.speedRatio = this._speedRatio;
  42418. }
  42419. },
  42420. enumerable: true,
  42421. configurable: true
  42422. });
  42423. /**
  42424. * Add an animation (with its target) in the group
  42425. * @param animation defines the animation we want to add
  42426. * @param target defines the target of the animation
  42427. * @returns the {BABYLON.TargetedAnimation} object
  42428. */
  42429. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42430. var targetedAnimation = {
  42431. animation: animation,
  42432. target: target
  42433. };
  42434. var keys = animation.getKeys();
  42435. if (this._from > keys[0].frame) {
  42436. this._from = keys[0].frame;
  42437. }
  42438. if (this._to < keys[keys.length - 1].frame) {
  42439. this._to = keys[keys.length - 1].frame;
  42440. }
  42441. this._targetedAnimations.push(targetedAnimation);
  42442. return targetedAnimation;
  42443. };
  42444. /**
  42445. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42446. * It can add constant keys at begin or end
  42447. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  42448. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  42449. */
  42450. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42451. beginFrame = Math.min(beginFrame, this._from);
  42452. endFrame = Math.min(endFrame, this._to);
  42453. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42454. var targetedAnimation = this._targetedAnimations[index];
  42455. var keys = targetedAnimation.animation.getKeys();
  42456. var startKey = keys[0];
  42457. var endKey = keys[keys.length - 1];
  42458. if (startKey.frame > beginFrame) {
  42459. var newKey = {
  42460. frame: beginFrame,
  42461. value: startKey.value,
  42462. inTangent: startKey.inTangent,
  42463. outTangent: startKey.outTangent
  42464. };
  42465. keys.splice(0, 0, newKey);
  42466. }
  42467. if (endKey.frame < endFrame) {
  42468. var newKey = {
  42469. frame: endFrame,
  42470. value: endKey.value,
  42471. inTangent: startKey.outTangent,
  42472. outTangent: startKey.outTangent
  42473. };
  42474. keys.push(newKey);
  42475. }
  42476. }
  42477. return this;
  42478. };
  42479. /**
  42480. * Start all animations on given targets
  42481. * @param loop defines if animations must loop
  42482. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42483. */
  42484. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42485. var _this = this;
  42486. if (loop === void 0) { loop = false; }
  42487. if (speedRatio === void 0) { speedRatio = 1; }
  42488. if (this._isStarted || this._targetedAnimations.length === 0) {
  42489. return this;
  42490. }
  42491. var _loop_1 = function () {
  42492. var targetedAnimation = this_1._targetedAnimations[index];
  42493. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42494. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42495. }));
  42496. };
  42497. var this_1 = this;
  42498. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42499. _loop_1();
  42500. }
  42501. this._speedRatio = speedRatio;
  42502. this._isStarted = true;
  42503. return this;
  42504. };
  42505. /**
  42506. * Pause all animations
  42507. */
  42508. AnimationGroup.prototype.pause = function () {
  42509. if (!this._isStarted) {
  42510. return this;
  42511. }
  42512. for (var index = 0; index < this._animatables.length; index++) {
  42513. var animatable = this._animatables[index];
  42514. animatable.pause();
  42515. }
  42516. return this;
  42517. };
  42518. /**
  42519. * Play all animations to initial state
  42520. * This function will start() the animations if they were not started or will restart() them if they were paused
  42521. * @param loop defines if animations must loop
  42522. */
  42523. AnimationGroup.prototype.play = function (loop) {
  42524. if (this.isStarted) {
  42525. if (loop !== undefined) {
  42526. for (var index = 0; index < this._animatables.length; index++) {
  42527. var animatable = this._animatables[index];
  42528. animatable.loopAnimation = loop;
  42529. }
  42530. }
  42531. this.restart();
  42532. }
  42533. else {
  42534. this.start(loop, this._speedRatio);
  42535. }
  42536. return this;
  42537. };
  42538. /**
  42539. * Reset all animations to initial state
  42540. */
  42541. AnimationGroup.prototype.reset = function () {
  42542. if (!this._isStarted) {
  42543. return this;
  42544. }
  42545. for (var index = 0; index < this._animatables.length; index++) {
  42546. var animatable = this._animatables[index];
  42547. animatable.reset();
  42548. }
  42549. return this;
  42550. };
  42551. /**
  42552. * Restart animations from key 0
  42553. */
  42554. AnimationGroup.prototype.restart = function () {
  42555. if (!this._isStarted) {
  42556. return this;
  42557. }
  42558. for (var index = 0; index < this._animatables.length; index++) {
  42559. var animatable = this._animatables[index];
  42560. animatable.restart();
  42561. }
  42562. return this;
  42563. };
  42564. /**
  42565. * Stop all animations
  42566. */
  42567. AnimationGroup.prototype.stop = function () {
  42568. if (!this._isStarted) {
  42569. return this;
  42570. }
  42571. for (var index = 0; index < this._animatables.length; index++) {
  42572. var animatable = this._animatables[index];
  42573. animatable.stop();
  42574. }
  42575. this._isStarted = false;
  42576. return this;
  42577. };
  42578. /**
  42579. * Dispose all associated resources
  42580. */
  42581. AnimationGroup.prototype.dispose = function () {
  42582. this._targetedAnimations = [];
  42583. this._animatables = [];
  42584. var index = this._scene.animationGroups.indexOf(this);
  42585. if (index > -1) {
  42586. this._scene.animationGroups.splice(index, 1);
  42587. }
  42588. };
  42589. return AnimationGroup;
  42590. }());
  42591. BABYLON.AnimationGroup = AnimationGroup;
  42592. })(BABYLON || (BABYLON = {}));
  42593. //# sourceMappingURL=babylon.animationGroup.js.map
  42594. var BABYLON;
  42595. (function (BABYLON) {
  42596. var RuntimeAnimation = /** @class */ (function () {
  42597. function RuntimeAnimation(target, animation) {
  42598. this._offsetsCache = {};
  42599. this._highLimitsCache = {};
  42600. this._stopped = false;
  42601. this._blendingFactor = 0;
  42602. this._ratioOffset = 0;
  42603. this._animation = animation;
  42604. this._target = target;
  42605. animation._runtimeAnimations.push(this);
  42606. }
  42607. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42608. get: function () {
  42609. return this._animation;
  42610. },
  42611. enumerable: true,
  42612. configurable: true
  42613. });
  42614. RuntimeAnimation.prototype.reset = function () {
  42615. this._offsetsCache = {};
  42616. this._highLimitsCache = {};
  42617. this.currentFrame = 0;
  42618. this._blendingFactor = 0;
  42619. this._originalBlendValue = null;
  42620. };
  42621. RuntimeAnimation.prototype.isStopped = function () {
  42622. return this._stopped;
  42623. };
  42624. RuntimeAnimation.prototype.dispose = function () {
  42625. var index = this._animation.runtimeAnimations.indexOf(this);
  42626. if (index > -1) {
  42627. this._animation.runtimeAnimations.splice(index, 1);
  42628. }
  42629. };
  42630. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42631. if (typeof value === "function") {
  42632. return value();
  42633. }
  42634. return value;
  42635. };
  42636. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42637. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42638. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42639. }
  42640. this.currentFrame = currentFrame;
  42641. var keys = this._animation.getKeys();
  42642. // Try to get a hash to find the right key
  42643. 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));
  42644. if (keys[startKeyIndex].frame >= currentFrame) {
  42645. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42646. startKeyIndex--;
  42647. }
  42648. }
  42649. for (var key = startKeyIndex; key < keys.length; key++) {
  42650. var endKey = keys[key + 1];
  42651. if (endKey.frame >= currentFrame) {
  42652. var startKey = keys[key];
  42653. var startValue = this._getKeyValue(startKey.value);
  42654. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42655. return startValue;
  42656. }
  42657. var endValue = this._getKeyValue(endKey.value);
  42658. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42659. var frameDelta = endKey.frame - startKey.frame;
  42660. // gradient : percent of currentFrame between the frame inf and the frame sup
  42661. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42662. // check for easingFunction and correction of gradient
  42663. var easingFunction = this._animation.getEasingFunction();
  42664. if (easingFunction != null) {
  42665. gradient = easingFunction.ease(gradient);
  42666. }
  42667. switch (this._animation.dataType) {
  42668. // Float
  42669. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42670. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42671. switch (loopMode) {
  42672. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42673. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42674. return floatValue;
  42675. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42676. return offsetValue * repeatCount + floatValue;
  42677. }
  42678. break;
  42679. // Quaternion
  42680. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42681. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42682. switch (loopMode) {
  42683. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42684. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42685. return quatValue;
  42686. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42687. return quatValue.add(offsetValue.scale(repeatCount));
  42688. }
  42689. return quatValue;
  42690. // Vector3
  42691. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42692. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42693. switch (loopMode) {
  42694. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42695. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42696. return vec3Value;
  42697. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42698. return vec3Value.add(offsetValue.scale(repeatCount));
  42699. }
  42700. // Vector2
  42701. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42702. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42703. switch (loopMode) {
  42704. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42705. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42706. return vec2Value;
  42707. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42708. return vec2Value.add(offsetValue.scale(repeatCount));
  42709. }
  42710. // Size
  42711. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42712. switch (loopMode) {
  42713. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42714. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42715. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42716. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42717. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42718. }
  42719. // Color3
  42720. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42721. switch (loopMode) {
  42722. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42723. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42724. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42725. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42726. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42727. }
  42728. // Matrix
  42729. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42730. switch (loopMode) {
  42731. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42732. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42733. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42734. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42735. }
  42736. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42737. return startValue;
  42738. }
  42739. default:
  42740. break;
  42741. }
  42742. break;
  42743. }
  42744. }
  42745. return this._getKeyValue(keys[keys.length - 1].value);
  42746. };
  42747. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42748. if (blend === void 0) { blend = false; }
  42749. // Set value
  42750. var path;
  42751. var destination;
  42752. var targetPropertyPath = this._animation.targetPropertyPath;
  42753. if (targetPropertyPath.length > 1) {
  42754. var property = this._target[targetPropertyPath[0]];
  42755. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42756. property = property[targetPropertyPath[index]];
  42757. }
  42758. path = targetPropertyPath[targetPropertyPath.length - 1];
  42759. destination = property;
  42760. }
  42761. else {
  42762. path = targetPropertyPath[0];
  42763. destination = this._target;
  42764. }
  42765. // Blending
  42766. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42767. if (!this._originalBlendValue) {
  42768. if (destination[path].clone) {
  42769. this._originalBlendValue = destination[path].clone();
  42770. }
  42771. else {
  42772. this._originalBlendValue = destination[path];
  42773. }
  42774. }
  42775. if (this._originalBlendValue.prototype) {
  42776. if (this._originalBlendValue.prototype.Lerp) {
  42777. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42778. }
  42779. else {
  42780. destination[path] = currentValue;
  42781. }
  42782. }
  42783. else if (this._originalBlendValue.m) {
  42784. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42785. }
  42786. else {
  42787. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42788. }
  42789. this._blendingFactor += this._animation.blendingSpeed;
  42790. }
  42791. else {
  42792. destination[path] = currentValue;
  42793. }
  42794. if (this._target.markAsDirty) {
  42795. this._target.markAsDirty(this._animation.targetProperty);
  42796. }
  42797. };
  42798. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42799. var keys = this._animation.getKeys();
  42800. if (frame < keys[0].frame) {
  42801. frame = keys[0].frame;
  42802. }
  42803. else if (frame > keys[keys.length - 1].frame) {
  42804. frame = keys[keys.length - 1].frame;
  42805. }
  42806. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42807. this.setValue(currentValue);
  42808. };
  42809. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42810. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42811. this._ratioOffset = this._previousRatio - newRatio;
  42812. };
  42813. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42814. if (blend === void 0) { blend = false; }
  42815. var targetPropertyPath = this._animation.targetPropertyPath;
  42816. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42817. this._stopped = true;
  42818. return false;
  42819. }
  42820. var returnValue = true;
  42821. var keys = this._animation.getKeys();
  42822. // Adding a start key at frame 0 if missing
  42823. if (keys[0].frame !== 0) {
  42824. var newKey = { frame: 0, value: keys[0].value };
  42825. keys.splice(0, 0, newKey);
  42826. }
  42827. // Check limits
  42828. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42829. from = keys[0].frame;
  42830. }
  42831. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42832. to = keys[keys.length - 1].frame;
  42833. }
  42834. //to and from cannot be the same key
  42835. if (from === to) {
  42836. if (from > keys[0].frame) {
  42837. from--;
  42838. }
  42839. else if (to < keys[keys.length - 1].frame) {
  42840. to++;
  42841. }
  42842. }
  42843. // Compute ratio
  42844. var range = to - from;
  42845. var offsetValue;
  42846. // ratio represents the frame delta between from and to
  42847. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42848. var highLimitValue = 0;
  42849. this._previousDelay = delay;
  42850. this._previousRatio = ratio;
  42851. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42852. returnValue = false;
  42853. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42854. }
  42855. else {
  42856. // Get max value if required
  42857. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42858. var keyOffset = to.toString() + from.toString();
  42859. if (!this._offsetsCache[keyOffset]) {
  42860. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42861. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42862. switch (this._animation.dataType) {
  42863. // Float
  42864. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42865. this._offsetsCache[keyOffset] = toValue - fromValue;
  42866. break;
  42867. // Quaternion
  42868. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42869. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42870. break;
  42871. // Vector3
  42872. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42873. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42874. // Vector2
  42875. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42876. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42877. // Size
  42878. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42879. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42880. // Color3
  42881. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42882. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42883. default:
  42884. break;
  42885. }
  42886. this._highLimitsCache[keyOffset] = toValue;
  42887. }
  42888. highLimitValue = this._highLimitsCache[keyOffset];
  42889. offsetValue = this._offsetsCache[keyOffset];
  42890. }
  42891. }
  42892. if (offsetValue === undefined) {
  42893. switch (this._animation.dataType) {
  42894. // Float
  42895. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42896. offsetValue = 0;
  42897. break;
  42898. // Quaternion
  42899. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42900. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42901. break;
  42902. // Vector3
  42903. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42904. offsetValue = BABYLON.Vector3.Zero();
  42905. break;
  42906. // Vector2
  42907. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42908. offsetValue = BABYLON.Vector2.Zero();
  42909. break;
  42910. // Size
  42911. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42912. offsetValue = BABYLON.Size.Zero();
  42913. break;
  42914. // Color3
  42915. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42916. offsetValue = BABYLON.Color3.Black();
  42917. }
  42918. }
  42919. // Compute value
  42920. var repeatCount = (ratio / range) >> 0;
  42921. var currentFrame = returnValue ? from + ratio % range : to;
  42922. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42923. // Set value
  42924. this.setValue(currentValue);
  42925. // Check events
  42926. var events = this._animation.getEvents();
  42927. for (var index = 0; index < events.length; index++) {
  42928. // Make sure current frame has passed event frame and that event frame is within the current range
  42929. // Also, handle both forward and reverse animations
  42930. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42931. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42932. var event = events[index];
  42933. if (!event.isDone) {
  42934. // If event should be done only once, remove it.
  42935. if (event.onlyOnce) {
  42936. events.splice(index, 1);
  42937. index--;
  42938. }
  42939. event.isDone = true;
  42940. event.action();
  42941. } // Don't do anything if the event has already be done.
  42942. }
  42943. else if (events[index].isDone && !events[index].onlyOnce) {
  42944. // reset event, the animation is looping
  42945. events[index].isDone = false;
  42946. }
  42947. }
  42948. if (!returnValue) {
  42949. this._stopped = true;
  42950. }
  42951. return returnValue;
  42952. };
  42953. return RuntimeAnimation;
  42954. }());
  42955. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42956. })(BABYLON || (BABYLON = {}));
  42957. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42958. var BABYLON;
  42959. (function (BABYLON) {
  42960. var Animatable = /** @class */ (function () {
  42961. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42962. if (fromFrame === void 0) { fromFrame = 0; }
  42963. if (toFrame === void 0) { toFrame = 100; }
  42964. if (loopAnimation === void 0) { loopAnimation = false; }
  42965. if (speedRatio === void 0) { speedRatio = 1.0; }
  42966. this.target = target;
  42967. this.fromFrame = fromFrame;
  42968. this.toFrame = toFrame;
  42969. this.loopAnimation = loopAnimation;
  42970. this.onAnimationEnd = onAnimationEnd;
  42971. this._localDelayOffset = null;
  42972. this._pausedDelay = null;
  42973. this._runtimeAnimations = new Array();
  42974. this._paused = false;
  42975. this._speedRatio = 1;
  42976. this.animationStarted = false;
  42977. if (animations) {
  42978. this.appendAnimations(target, animations);
  42979. }
  42980. this._speedRatio = speedRatio;
  42981. this._scene = scene;
  42982. scene._activeAnimatables.push(this);
  42983. }
  42984. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42985. get: function () {
  42986. return this._speedRatio;
  42987. },
  42988. set: function (value) {
  42989. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42990. var animation = this._runtimeAnimations[index];
  42991. animation._prepareForSpeedRatioChange(value);
  42992. }
  42993. this._speedRatio = value;
  42994. },
  42995. enumerable: true,
  42996. configurable: true
  42997. });
  42998. // Methods
  42999. Animatable.prototype.getAnimations = function () {
  43000. return this._runtimeAnimations;
  43001. };
  43002. Animatable.prototype.appendAnimations = function (target, animations) {
  43003. for (var index = 0; index < animations.length; index++) {
  43004. var animation = animations[index];
  43005. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43006. }
  43007. };
  43008. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43009. var runtimeAnimations = this._runtimeAnimations;
  43010. for (var index = 0; index < runtimeAnimations.length; index++) {
  43011. if (runtimeAnimations[index].animation.targetProperty === property) {
  43012. return runtimeAnimations[index].animation;
  43013. }
  43014. }
  43015. return null;
  43016. };
  43017. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43018. var runtimeAnimations = this._runtimeAnimations;
  43019. for (var index = 0; index < runtimeAnimations.length; index++) {
  43020. if (runtimeAnimations[index].animation.targetProperty === property) {
  43021. return runtimeAnimations[index];
  43022. }
  43023. }
  43024. return null;
  43025. };
  43026. Animatable.prototype.reset = function () {
  43027. var runtimeAnimations = this._runtimeAnimations;
  43028. for (var index = 0; index < runtimeAnimations.length; index++) {
  43029. runtimeAnimations[index].reset();
  43030. }
  43031. // Reset to original value
  43032. for (index = 0; index < runtimeAnimations.length; index++) {
  43033. var animation = runtimeAnimations[index];
  43034. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43035. }
  43036. this._localDelayOffset = null;
  43037. this._pausedDelay = null;
  43038. };
  43039. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43040. var runtimeAnimations = this._runtimeAnimations;
  43041. for (var index = 0; index < runtimeAnimations.length; index++) {
  43042. runtimeAnimations[index].animation.enableBlending = true;
  43043. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43044. }
  43045. };
  43046. Animatable.prototype.disableBlending = function () {
  43047. var runtimeAnimations = this._runtimeAnimations;
  43048. for (var index = 0; index < runtimeAnimations.length; index++) {
  43049. runtimeAnimations[index].animation.enableBlending = false;
  43050. }
  43051. };
  43052. Animatable.prototype.goToFrame = function (frame) {
  43053. var runtimeAnimations = this._runtimeAnimations;
  43054. if (runtimeAnimations[0]) {
  43055. var fps = runtimeAnimations[0].animation.framePerSecond;
  43056. var currentFrame = runtimeAnimations[0].currentFrame;
  43057. var adjustTime = frame - currentFrame;
  43058. var delay = adjustTime * 1000 / fps;
  43059. if (this._localDelayOffset === null) {
  43060. this._localDelayOffset = 0;
  43061. }
  43062. this._localDelayOffset -= delay;
  43063. }
  43064. for (var index = 0; index < runtimeAnimations.length; index++) {
  43065. runtimeAnimations[index].goToFrame(frame);
  43066. }
  43067. };
  43068. Animatable.prototype.pause = function () {
  43069. if (this._paused) {
  43070. return;
  43071. }
  43072. this._paused = true;
  43073. };
  43074. Animatable.prototype.restart = function () {
  43075. this._paused = false;
  43076. };
  43077. Animatable.prototype.stop = function (animationName) {
  43078. if (animationName) {
  43079. var idx = this._scene._activeAnimatables.indexOf(this);
  43080. if (idx > -1) {
  43081. var runtimeAnimations = this._runtimeAnimations;
  43082. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43083. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43084. continue;
  43085. }
  43086. runtimeAnimations[index].dispose();
  43087. runtimeAnimations.splice(index, 1);
  43088. }
  43089. if (runtimeAnimations.length == 0) {
  43090. this._scene._activeAnimatables.splice(idx, 1);
  43091. if (this.onAnimationEnd) {
  43092. this.onAnimationEnd();
  43093. }
  43094. }
  43095. }
  43096. }
  43097. else {
  43098. var index = this._scene._activeAnimatables.indexOf(this);
  43099. if (index > -1) {
  43100. this._scene._activeAnimatables.splice(index, 1);
  43101. var runtimeAnimations = this._runtimeAnimations;
  43102. for (var index = 0; index < runtimeAnimations.length; index++) {
  43103. runtimeAnimations[index].dispose();
  43104. }
  43105. if (this.onAnimationEnd) {
  43106. this.onAnimationEnd();
  43107. }
  43108. }
  43109. }
  43110. };
  43111. Animatable.prototype._animate = function (delay) {
  43112. if (this._paused) {
  43113. this.animationStarted = false;
  43114. if (this._pausedDelay === null) {
  43115. this._pausedDelay = delay;
  43116. }
  43117. return true;
  43118. }
  43119. if (this._localDelayOffset === null) {
  43120. this._localDelayOffset = delay;
  43121. }
  43122. else if (this._pausedDelay !== null) {
  43123. this._localDelayOffset += delay - this._pausedDelay;
  43124. this._pausedDelay = null;
  43125. }
  43126. // Animating
  43127. var running = false;
  43128. var runtimeAnimations = this._runtimeAnimations;
  43129. var index;
  43130. for (index = 0; index < runtimeAnimations.length; index++) {
  43131. var animation = runtimeAnimations[index];
  43132. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43133. running = running || isRunning;
  43134. }
  43135. this.animationStarted = running;
  43136. if (!running) {
  43137. // Remove from active animatables
  43138. index = this._scene._activeAnimatables.indexOf(this);
  43139. this._scene._activeAnimatables.splice(index, 1);
  43140. // Dispose all runtime animations
  43141. for (index = 0; index < runtimeAnimations.length; index++) {
  43142. runtimeAnimations[index].dispose();
  43143. }
  43144. }
  43145. if (!running && this.onAnimationEnd) {
  43146. this.onAnimationEnd();
  43147. this.onAnimationEnd = null;
  43148. }
  43149. return running;
  43150. };
  43151. return Animatable;
  43152. }());
  43153. BABYLON.Animatable = Animatable;
  43154. })(BABYLON || (BABYLON = {}));
  43155. //# sourceMappingURL=babylon.animatable.js.map
  43156. var BABYLON;
  43157. (function (BABYLON) {
  43158. var EasingFunction = /** @class */ (function () {
  43159. function EasingFunction() {
  43160. // Properties
  43161. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43162. }
  43163. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43164. get: function () {
  43165. return EasingFunction._EASINGMODE_EASEIN;
  43166. },
  43167. enumerable: true,
  43168. configurable: true
  43169. });
  43170. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43171. get: function () {
  43172. return EasingFunction._EASINGMODE_EASEOUT;
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43178. get: function () {
  43179. return EasingFunction._EASINGMODE_EASEINOUT;
  43180. },
  43181. enumerable: true,
  43182. configurable: true
  43183. });
  43184. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43185. var n = Math.min(Math.max(easingMode, 0), 2);
  43186. this._easingMode = n;
  43187. };
  43188. EasingFunction.prototype.getEasingMode = function () {
  43189. return this._easingMode;
  43190. };
  43191. EasingFunction.prototype.easeInCore = function (gradient) {
  43192. throw new Error('You must implement this method');
  43193. };
  43194. EasingFunction.prototype.ease = function (gradient) {
  43195. switch (this._easingMode) {
  43196. case EasingFunction.EASINGMODE_EASEIN:
  43197. return this.easeInCore(gradient);
  43198. case EasingFunction.EASINGMODE_EASEOUT:
  43199. return (1 - this.easeInCore(1 - gradient));
  43200. }
  43201. if (gradient >= 0.5) {
  43202. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43203. }
  43204. return (this.easeInCore(gradient * 2) * 0.5);
  43205. };
  43206. //Statics
  43207. EasingFunction._EASINGMODE_EASEIN = 0;
  43208. EasingFunction._EASINGMODE_EASEOUT = 1;
  43209. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43210. return EasingFunction;
  43211. }());
  43212. BABYLON.EasingFunction = EasingFunction;
  43213. var CircleEase = /** @class */ (function (_super) {
  43214. __extends(CircleEase, _super);
  43215. function CircleEase() {
  43216. return _super !== null && _super.apply(this, arguments) || this;
  43217. }
  43218. CircleEase.prototype.easeInCore = function (gradient) {
  43219. gradient = Math.max(0, Math.min(1, gradient));
  43220. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43221. };
  43222. return CircleEase;
  43223. }(EasingFunction));
  43224. BABYLON.CircleEase = CircleEase;
  43225. var BackEase = /** @class */ (function (_super) {
  43226. __extends(BackEase, _super);
  43227. function BackEase(amplitude) {
  43228. if (amplitude === void 0) { amplitude = 1; }
  43229. var _this = _super.call(this) || this;
  43230. _this.amplitude = amplitude;
  43231. return _this;
  43232. }
  43233. BackEase.prototype.easeInCore = function (gradient) {
  43234. var num = Math.max(0, this.amplitude);
  43235. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43236. };
  43237. return BackEase;
  43238. }(EasingFunction));
  43239. BABYLON.BackEase = BackEase;
  43240. var BounceEase = /** @class */ (function (_super) {
  43241. __extends(BounceEase, _super);
  43242. function BounceEase(bounces, bounciness) {
  43243. if (bounces === void 0) { bounces = 3; }
  43244. if (bounciness === void 0) { bounciness = 2; }
  43245. var _this = _super.call(this) || this;
  43246. _this.bounces = bounces;
  43247. _this.bounciness = bounciness;
  43248. return _this;
  43249. }
  43250. BounceEase.prototype.easeInCore = function (gradient) {
  43251. var y = Math.max(0.0, this.bounces);
  43252. var bounciness = this.bounciness;
  43253. if (bounciness <= 1.0) {
  43254. bounciness = 1.001;
  43255. }
  43256. var num9 = Math.pow(bounciness, y);
  43257. var num5 = 1.0 - bounciness;
  43258. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43259. var num15 = gradient * num4;
  43260. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43261. var num3 = Math.floor(num65);
  43262. var num13 = num3 + 1.0;
  43263. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43264. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43265. var num7 = (num8 + num12) * 0.5;
  43266. var num6 = gradient - num7;
  43267. var num2 = num7 - num8;
  43268. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43269. };
  43270. return BounceEase;
  43271. }(EasingFunction));
  43272. BABYLON.BounceEase = BounceEase;
  43273. var CubicEase = /** @class */ (function (_super) {
  43274. __extends(CubicEase, _super);
  43275. function CubicEase() {
  43276. return _super !== null && _super.apply(this, arguments) || this;
  43277. }
  43278. CubicEase.prototype.easeInCore = function (gradient) {
  43279. return (gradient * gradient * gradient);
  43280. };
  43281. return CubicEase;
  43282. }(EasingFunction));
  43283. BABYLON.CubicEase = CubicEase;
  43284. var ElasticEase = /** @class */ (function (_super) {
  43285. __extends(ElasticEase, _super);
  43286. function ElasticEase(oscillations, springiness) {
  43287. if (oscillations === void 0) { oscillations = 3; }
  43288. if (springiness === void 0) { springiness = 3; }
  43289. var _this = _super.call(this) || this;
  43290. _this.oscillations = oscillations;
  43291. _this.springiness = springiness;
  43292. return _this;
  43293. }
  43294. ElasticEase.prototype.easeInCore = function (gradient) {
  43295. var num2;
  43296. var num3 = Math.max(0.0, this.oscillations);
  43297. var num = Math.max(0.0, this.springiness);
  43298. if (num == 0) {
  43299. num2 = gradient;
  43300. }
  43301. else {
  43302. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43303. }
  43304. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43305. };
  43306. return ElasticEase;
  43307. }(EasingFunction));
  43308. BABYLON.ElasticEase = ElasticEase;
  43309. var ExponentialEase = /** @class */ (function (_super) {
  43310. __extends(ExponentialEase, _super);
  43311. function ExponentialEase(exponent) {
  43312. if (exponent === void 0) { exponent = 2; }
  43313. var _this = _super.call(this) || this;
  43314. _this.exponent = exponent;
  43315. return _this;
  43316. }
  43317. ExponentialEase.prototype.easeInCore = function (gradient) {
  43318. if (this.exponent <= 0) {
  43319. return gradient;
  43320. }
  43321. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43322. };
  43323. return ExponentialEase;
  43324. }(EasingFunction));
  43325. BABYLON.ExponentialEase = ExponentialEase;
  43326. var PowerEase = /** @class */ (function (_super) {
  43327. __extends(PowerEase, _super);
  43328. function PowerEase(power) {
  43329. if (power === void 0) { power = 2; }
  43330. var _this = _super.call(this) || this;
  43331. _this.power = power;
  43332. return _this;
  43333. }
  43334. PowerEase.prototype.easeInCore = function (gradient) {
  43335. var y = Math.max(0.0, this.power);
  43336. return Math.pow(gradient, y);
  43337. };
  43338. return PowerEase;
  43339. }(EasingFunction));
  43340. BABYLON.PowerEase = PowerEase;
  43341. var QuadraticEase = /** @class */ (function (_super) {
  43342. __extends(QuadraticEase, _super);
  43343. function QuadraticEase() {
  43344. return _super !== null && _super.apply(this, arguments) || this;
  43345. }
  43346. QuadraticEase.prototype.easeInCore = function (gradient) {
  43347. return (gradient * gradient);
  43348. };
  43349. return QuadraticEase;
  43350. }(EasingFunction));
  43351. BABYLON.QuadraticEase = QuadraticEase;
  43352. var QuarticEase = /** @class */ (function (_super) {
  43353. __extends(QuarticEase, _super);
  43354. function QuarticEase() {
  43355. return _super !== null && _super.apply(this, arguments) || this;
  43356. }
  43357. QuarticEase.prototype.easeInCore = function (gradient) {
  43358. return (gradient * gradient * gradient * gradient);
  43359. };
  43360. return QuarticEase;
  43361. }(EasingFunction));
  43362. BABYLON.QuarticEase = QuarticEase;
  43363. var QuinticEase = /** @class */ (function (_super) {
  43364. __extends(QuinticEase, _super);
  43365. function QuinticEase() {
  43366. return _super !== null && _super.apply(this, arguments) || this;
  43367. }
  43368. QuinticEase.prototype.easeInCore = function (gradient) {
  43369. return (gradient * gradient * gradient * gradient * gradient);
  43370. };
  43371. return QuinticEase;
  43372. }(EasingFunction));
  43373. BABYLON.QuinticEase = QuinticEase;
  43374. var SineEase = /** @class */ (function (_super) {
  43375. __extends(SineEase, _super);
  43376. function SineEase() {
  43377. return _super !== null && _super.apply(this, arguments) || this;
  43378. }
  43379. SineEase.prototype.easeInCore = function (gradient) {
  43380. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43381. };
  43382. return SineEase;
  43383. }(EasingFunction));
  43384. BABYLON.SineEase = SineEase;
  43385. var BezierCurveEase = /** @class */ (function (_super) {
  43386. __extends(BezierCurveEase, _super);
  43387. function BezierCurveEase(x1, y1, x2, y2) {
  43388. if (x1 === void 0) { x1 = 0; }
  43389. if (y1 === void 0) { y1 = 0; }
  43390. if (x2 === void 0) { x2 = 1; }
  43391. if (y2 === void 0) { y2 = 1; }
  43392. var _this = _super.call(this) || this;
  43393. _this.x1 = x1;
  43394. _this.y1 = y1;
  43395. _this.x2 = x2;
  43396. _this.y2 = y2;
  43397. return _this;
  43398. }
  43399. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43400. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43401. };
  43402. return BezierCurveEase;
  43403. }(EasingFunction));
  43404. BABYLON.BezierCurveEase = BezierCurveEase;
  43405. })(BABYLON || (BABYLON = {}));
  43406. //# sourceMappingURL=babylon.easing.js.map
  43407. var BABYLON;
  43408. (function (BABYLON) {
  43409. var Condition = /** @class */ (function () {
  43410. function Condition(actionManager) {
  43411. this._actionManager = actionManager;
  43412. }
  43413. Condition.prototype.isValid = function () {
  43414. return true;
  43415. };
  43416. Condition.prototype._getProperty = function (propertyPath) {
  43417. return this._actionManager._getProperty(propertyPath);
  43418. };
  43419. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43420. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43421. };
  43422. Condition.prototype.serialize = function () {
  43423. };
  43424. Condition.prototype._serialize = function (serializedCondition) {
  43425. return {
  43426. type: 2,
  43427. children: [],
  43428. name: serializedCondition.name,
  43429. properties: serializedCondition.properties
  43430. };
  43431. };
  43432. return Condition;
  43433. }());
  43434. BABYLON.Condition = Condition;
  43435. var ValueCondition = /** @class */ (function (_super) {
  43436. __extends(ValueCondition, _super);
  43437. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43438. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43439. var _this = _super.call(this, actionManager) || this;
  43440. _this.propertyPath = propertyPath;
  43441. _this.value = value;
  43442. _this.operator = operator;
  43443. _this._target = target;
  43444. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43445. _this._property = _this._getProperty(_this.propertyPath);
  43446. return _this;
  43447. }
  43448. Object.defineProperty(ValueCondition, "IsEqual", {
  43449. get: function () {
  43450. return ValueCondition._IsEqual;
  43451. },
  43452. enumerable: true,
  43453. configurable: true
  43454. });
  43455. Object.defineProperty(ValueCondition, "IsDifferent", {
  43456. get: function () {
  43457. return ValueCondition._IsDifferent;
  43458. },
  43459. enumerable: true,
  43460. configurable: true
  43461. });
  43462. Object.defineProperty(ValueCondition, "IsGreater", {
  43463. get: function () {
  43464. return ValueCondition._IsGreater;
  43465. },
  43466. enumerable: true,
  43467. configurable: true
  43468. });
  43469. Object.defineProperty(ValueCondition, "IsLesser", {
  43470. get: function () {
  43471. return ValueCondition._IsLesser;
  43472. },
  43473. enumerable: true,
  43474. configurable: true
  43475. });
  43476. // Methods
  43477. ValueCondition.prototype.isValid = function () {
  43478. switch (this.operator) {
  43479. case ValueCondition.IsGreater:
  43480. return this._effectiveTarget[this._property] > this.value;
  43481. case ValueCondition.IsLesser:
  43482. return this._effectiveTarget[this._property] < this.value;
  43483. case ValueCondition.IsEqual:
  43484. case ValueCondition.IsDifferent:
  43485. var check;
  43486. if (this.value.equals) {
  43487. check = this.value.equals(this._effectiveTarget[this._property]);
  43488. }
  43489. else {
  43490. check = this.value === this._effectiveTarget[this._property];
  43491. }
  43492. return this.operator === ValueCondition.IsEqual ? check : !check;
  43493. }
  43494. return false;
  43495. };
  43496. ValueCondition.prototype.serialize = function () {
  43497. return this._serialize({
  43498. name: "ValueCondition",
  43499. properties: [
  43500. BABYLON.Action._GetTargetProperty(this._target),
  43501. { name: "propertyPath", value: this.propertyPath },
  43502. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43503. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43504. ]
  43505. });
  43506. };
  43507. ValueCondition.GetOperatorName = function (operator) {
  43508. switch (operator) {
  43509. case ValueCondition._IsEqual: return "IsEqual";
  43510. case ValueCondition._IsDifferent: return "IsDifferent";
  43511. case ValueCondition._IsGreater: return "IsGreater";
  43512. case ValueCondition._IsLesser: return "IsLesser";
  43513. default: return "";
  43514. }
  43515. };
  43516. // Statics
  43517. ValueCondition._IsEqual = 0;
  43518. ValueCondition._IsDifferent = 1;
  43519. ValueCondition._IsGreater = 2;
  43520. ValueCondition._IsLesser = 3;
  43521. return ValueCondition;
  43522. }(Condition));
  43523. BABYLON.ValueCondition = ValueCondition;
  43524. var PredicateCondition = /** @class */ (function (_super) {
  43525. __extends(PredicateCondition, _super);
  43526. function PredicateCondition(actionManager, predicate) {
  43527. var _this = _super.call(this, actionManager) || this;
  43528. _this.predicate = predicate;
  43529. return _this;
  43530. }
  43531. PredicateCondition.prototype.isValid = function () {
  43532. return this.predicate();
  43533. };
  43534. return PredicateCondition;
  43535. }(Condition));
  43536. BABYLON.PredicateCondition = PredicateCondition;
  43537. var StateCondition = /** @class */ (function (_super) {
  43538. __extends(StateCondition, _super);
  43539. function StateCondition(actionManager, target, value) {
  43540. var _this = _super.call(this, actionManager) || this;
  43541. _this.value = value;
  43542. _this._target = target;
  43543. return _this;
  43544. }
  43545. // Methods
  43546. StateCondition.prototype.isValid = function () {
  43547. return this._target.state === this.value;
  43548. };
  43549. StateCondition.prototype.serialize = function () {
  43550. return this._serialize({
  43551. name: "StateCondition",
  43552. properties: [
  43553. BABYLON.Action._GetTargetProperty(this._target),
  43554. { name: "value", value: this.value }
  43555. ]
  43556. });
  43557. };
  43558. return StateCondition;
  43559. }(Condition));
  43560. BABYLON.StateCondition = StateCondition;
  43561. })(BABYLON || (BABYLON = {}));
  43562. //# sourceMappingURL=babylon.condition.js.map
  43563. var BABYLON;
  43564. (function (BABYLON) {
  43565. var Action = /** @class */ (function () {
  43566. function Action(triggerOptions, condition) {
  43567. this.triggerOptions = triggerOptions;
  43568. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43569. if (triggerOptions.parameter) {
  43570. this.trigger = triggerOptions.trigger;
  43571. this._triggerParameter = triggerOptions.parameter;
  43572. }
  43573. else {
  43574. this.trigger = triggerOptions;
  43575. }
  43576. this._nextActiveAction = this;
  43577. this._condition = condition;
  43578. }
  43579. // Methods
  43580. Action.prototype._prepare = function () {
  43581. };
  43582. Action.prototype.getTriggerParameter = function () {
  43583. return this._triggerParameter;
  43584. };
  43585. Action.prototype._executeCurrent = function (evt) {
  43586. if (this._nextActiveAction._condition) {
  43587. var condition = this._nextActiveAction._condition;
  43588. var currentRenderId = this._actionManager.getScene().getRenderId();
  43589. // We cache the current evaluation for the current frame
  43590. if (condition._evaluationId === currentRenderId) {
  43591. if (!condition._currentResult) {
  43592. return;
  43593. }
  43594. }
  43595. else {
  43596. condition._evaluationId = currentRenderId;
  43597. if (!condition.isValid()) {
  43598. condition._currentResult = false;
  43599. return;
  43600. }
  43601. condition._currentResult = true;
  43602. }
  43603. }
  43604. this.onBeforeExecuteObservable.notifyObservers(this);
  43605. this._nextActiveAction.execute(evt);
  43606. this.skipToNextActiveAction();
  43607. };
  43608. Action.prototype.execute = function (evt) {
  43609. };
  43610. Action.prototype.skipToNextActiveAction = function () {
  43611. if (this._nextActiveAction._child) {
  43612. if (!this._nextActiveAction._child._actionManager) {
  43613. this._nextActiveAction._child._actionManager = this._actionManager;
  43614. }
  43615. this._nextActiveAction = this._nextActiveAction._child;
  43616. }
  43617. else {
  43618. this._nextActiveAction = this;
  43619. }
  43620. };
  43621. Action.prototype.then = function (action) {
  43622. this._child = action;
  43623. action._actionManager = this._actionManager;
  43624. action._prepare();
  43625. return action;
  43626. };
  43627. Action.prototype._getProperty = function (propertyPath) {
  43628. return this._actionManager._getProperty(propertyPath);
  43629. };
  43630. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43631. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43632. };
  43633. Action.prototype.serialize = function (parent) {
  43634. };
  43635. // Called by BABYLON.Action objects in serialize(...). Internal use
  43636. Action.prototype._serialize = function (serializedAction, parent) {
  43637. var serializationObject = {
  43638. type: 1,
  43639. children: [],
  43640. name: serializedAction.name,
  43641. properties: serializedAction.properties || []
  43642. };
  43643. // Serialize child
  43644. if (this._child) {
  43645. this._child.serialize(serializationObject);
  43646. }
  43647. // Check if "this" has a condition
  43648. if (this._condition) {
  43649. var serializedCondition = this._condition.serialize();
  43650. serializedCondition.children.push(serializationObject);
  43651. if (parent) {
  43652. parent.children.push(serializedCondition);
  43653. }
  43654. return serializedCondition;
  43655. }
  43656. if (parent) {
  43657. parent.children.push(serializationObject);
  43658. }
  43659. return serializationObject;
  43660. };
  43661. Action._SerializeValueAsString = function (value) {
  43662. if (typeof value === "number") {
  43663. return value.toString();
  43664. }
  43665. if (typeof value === "boolean") {
  43666. return value ? "true" : "false";
  43667. }
  43668. if (value instanceof BABYLON.Vector2) {
  43669. return value.x + ", " + value.y;
  43670. }
  43671. if (value instanceof BABYLON.Vector3) {
  43672. return value.x + ", " + value.y + ", " + value.z;
  43673. }
  43674. if (value instanceof BABYLON.Color3) {
  43675. return value.r + ", " + value.g + ", " + value.b;
  43676. }
  43677. if (value instanceof BABYLON.Color4) {
  43678. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43679. }
  43680. return value; // string
  43681. };
  43682. Action._GetTargetProperty = function (target) {
  43683. return {
  43684. name: "target",
  43685. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43686. : target instanceof BABYLON.Light ? "LightProperties"
  43687. : target instanceof BABYLON.Camera ? "CameraProperties"
  43688. : "SceneProperties",
  43689. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43690. };
  43691. };
  43692. return Action;
  43693. }());
  43694. BABYLON.Action = Action;
  43695. })(BABYLON || (BABYLON = {}));
  43696. //# sourceMappingURL=babylon.action.js.map
  43697. var BABYLON;
  43698. (function (BABYLON) {
  43699. /**
  43700. * ActionEvent is the event beint sent when an action is triggered.
  43701. */
  43702. var ActionEvent = /** @class */ (function () {
  43703. /**
  43704. * @param source The mesh or sprite that triggered the action.
  43705. * @param pointerX The X mouse cursor position at the time of the event
  43706. * @param pointerY The Y mouse cursor position at the time of the event
  43707. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43708. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43709. */
  43710. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43711. this.source = source;
  43712. this.pointerX = pointerX;
  43713. this.pointerY = pointerY;
  43714. this.meshUnderPointer = meshUnderPointer;
  43715. this.sourceEvent = sourceEvent;
  43716. this.additionalData = additionalData;
  43717. }
  43718. /**
  43719. * Helper function to auto-create an ActionEvent from a source mesh.
  43720. * @param source The source mesh that triggered the event
  43721. * @param evt {Event} The original (browser) event
  43722. */
  43723. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43724. var scene = source.getScene();
  43725. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43726. };
  43727. /**
  43728. * Helper function to auto-create an ActionEvent from a source mesh.
  43729. * @param source The source sprite that triggered the event
  43730. * @param scene Scene associated with the sprite
  43731. * @param evt {Event} The original (browser) event
  43732. */
  43733. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43734. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43735. };
  43736. /**
  43737. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43738. * @param scene the scene where the event occurred
  43739. * @param evt {Event} The original (browser) event
  43740. */
  43741. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43742. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43743. };
  43744. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43745. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43746. };
  43747. return ActionEvent;
  43748. }());
  43749. BABYLON.ActionEvent = ActionEvent;
  43750. /**
  43751. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43752. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43753. */
  43754. var ActionManager = /** @class */ (function () {
  43755. function ActionManager(scene) {
  43756. // Members
  43757. this.actions = new Array();
  43758. this.hoverCursor = '';
  43759. this._scene = scene;
  43760. scene._actionManagers.push(this);
  43761. }
  43762. Object.defineProperty(ActionManager, "NothingTrigger", {
  43763. get: function () {
  43764. return ActionManager._NothingTrigger;
  43765. },
  43766. enumerable: true,
  43767. configurable: true
  43768. });
  43769. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43770. get: function () {
  43771. return ActionManager._OnPickTrigger;
  43772. },
  43773. enumerable: true,
  43774. configurable: true
  43775. });
  43776. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43777. get: function () {
  43778. return ActionManager._OnLeftPickTrigger;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43784. get: function () {
  43785. return ActionManager._OnRightPickTrigger;
  43786. },
  43787. enumerable: true,
  43788. configurable: true
  43789. });
  43790. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43791. get: function () {
  43792. return ActionManager._OnCenterPickTrigger;
  43793. },
  43794. enumerable: true,
  43795. configurable: true
  43796. });
  43797. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43798. get: function () {
  43799. return ActionManager._OnPickDownTrigger;
  43800. },
  43801. enumerable: true,
  43802. configurable: true
  43803. });
  43804. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43805. get: function () {
  43806. return ActionManager._OnDoublePickTrigger;
  43807. },
  43808. enumerable: true,
  43809. configurable: true
  43810. });
  43811. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43812. get: function () {
  43813. return ActionManager._OnPickUpTrigger;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43819. /// This trigger will only be raised if you also declared a OnPickDown
  43820. get: function () {
  43821. return ActionManager._OnPickOutTrigger;
  43822. },
  43823. enumerable: true,
  43824. configurable: true
  43825. });
  43826. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43827. get: function () {
  43828. return ActionManager._OnLongPressTrigger;
  43829. },
  43830. enumerable: true,
  43831. configurable: true
  43832. });
  43833. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43834. get: function () {
  43835. return ActionManager._OnPointerOverTrigger;
  43836. },
  43837. enumerable: true,
  43838. configurable: true
  43839. });
  43840. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43841. get: function () {
  43842. return ActionManager._OnPointerOutTrigger;
  43843. },
  43844. enumerable: true,
  43845. configurable: true
  43846. });
  43847. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43848. get: function () {
  43849. return ActionManager._OnEveryFrameTrigger;
  43850. },
  43851. enumerable: true,
  43852. configurable: true
  43853. });
  43854. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43855. get: function () {
  43856. return ActionManager._OnIntersectionEnterTrigger;
  43857. },
  43858. enumerable: true,
  43859. configurable: true
  43860. });
  43861. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43862. get: function () {
  43863. return ActionManager._OnIntersectionExitTrigger;
  43864. },
  43865. enumerable: true,
  43866. configurable: true
  43867. });
  43868. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43869. get: function () {
  43870. return ActionManager._OnKeyDownTrigger;
  43871. },
  43872. enumerable: true,
  43873. configurable: true
  43874. });
  43875. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43876. get: function () {
  43877. return ActionManager._OnKeyUpTrigger;
  43878. },
  43879. enumerable: true,
  43880. configurable: true
  43881. });
  43882. // Methods
  43883. ActionManager.prototype.dispose = function () {
  43884. var index = this._scene._actionManagers.indexOf(this);
  43885. for (var i = 0; i < this.actions.length; i++) {
  43886. var action = this.actions[i];
  43887. ActionManager.Triggers[action.trigger]--;
  43888. if (ActionManager.Triggers[action.trigger] === 0) {
  43889. delete ActionManager.Triggers[action.trigger];
  43890. }
  43891. }
  43892. if (index > -1) {
  43893. this._scene._actionManagers.splice(index, 1);
  43894. }
  43895. };
  43896. ActionManager.prototype.getScene = function () {
  43897. return this._scene;
  43898. };
  43899. /**
  43900. * Does this action manager handles actions of any of the given triggers
  43901. * @param {number[]} triggers - the triggers to be tested
  43902. * @return {boolean} whether one (or more) of the triggers is handeled
  43903. */
  43904. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43905. for (var index = 0; index < this.actions.length; index++) {
  43906. var action = this.actions[index];
  43907. if (triggers.indexOf(action.trigger) > -1) {
  43908. return true;
  43909. }
  43910. }
  43911. return false;
  43912. };
  43913. /**
  43914. * Does this action manager handles actions of a given trigger
  43915. * @param {number} trigger - the trigger to be tested
  43916. * @return {boolean} whether the trigger is handeled
  43917. */
  43918. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43919. for (var index = 0; index < this.actions.length; index++) {
  43920. var action = this.actions[index];
  43921. if (action.trigger === trigger) {
  43922. return true;
  43923. }
  43924. }
  43925. return false;
  43926. };
  43927. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43928. /**
  43929. * Does this action manager has pointer triggers
  43930. * @return {boolean} whether or not it has pointer triggers
  43931. */
  43932. get: function () {
  43933. for (var index = 0; index < this.actions.length; index++) {
  43934. var action = this.actions[index];
  43935. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43936. return true;
  43937. }
  43938. }
  43939. return false;
  43940. },
  43941. enumerable: true,
  43942. configurable: true
  43943. });
  43944. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43945. /**
  43946. * Does this action manager has pick triggers
  43947. * @return {boolean} whether or not it has pick triggers
  43948. */
  43949. get: function () {
  43950. for (var index = 0; index < this.actions.length; index++) {
  43951. var action = this.actions[index];
  43952. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43953. return true;
  43954. }
  43955. }
  43956. return false;
  43957. },
  43958. enumerable: true,
  43959. configurable: true
  43960. });
  43961. Object.defineProperty(ActionManager, "HasTriggers", {
  43962. /**
  43963. * Does exist one action manager with at least one trigger
  43964. * @return {boolean} whether or not it exists one action manager with one trigger
  43965. **/
  43966. get: function () {
  43967. for (var t in ActionManager.Triggers) {
  43968. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43969. return true;
  43970. }
  43971. }
  43972. return false;
  43973. },
  43974. enumerable: true,
  43975. configurable: true
  43976. });
  43977. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43978. /**
  43979. * Does exist one action manager with at least one pick trigger
  43980. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43981. **/
  43982. get: function () {
  43983. for (var t in ActionManager.Triggers) {
  43984. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43985. var t_int = parseInt(t);
  43986. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43987. return true;
  43988. }
  43989. }
  43990. }
  43991. return false;
  43992. },
  43993. enumerable: true,
  43994. configurable: true
  43995. });
  43996. /**
  43997. * Does exist one action manager that handles actions of a given trigger
  43998. * @param {number} trigger - the trigger to be tested
  43999. * @return {boolean} whether the trigger is handeled by at least one action manager
  44000. **/
  44001. ActionManager.HasSpecificTrigger = function (trigger) {
  44002. for (var t in ActionManager.Triggers) {
  44003. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44004. var t_int = parseInt(t);
  44005. if (t_int === trigger) {
  44006. return true;
  44007. }
  44008. }
  44009. }
  44010. return false;
  44011. };
  44012. /**
  44013. * Registers an action to this action manager
  44014. * @param {BABYLON.Action} action - the action to be registered
  44015. * @return {BABYLON.Action} the action amended (prepared) after registration
  44016. */
  44017. ActionManager.prototype.registerAction = function (action) {
  44018. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44019. if (this.getScene().actionManager !== this) {
  44020. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44021. return null;
  44022. }
  44023. }
  44024. this.actions.push(action);
  44025. if (ActionManager.Triggers[action.trigger]) {
  44026. ActionManager.Triggers[action.trigger]++;
  44027. }
  44028. else {
  44029. ActionManager.Triggers[action.trigger] = 1;
  44030. }
  44031. action._actionManager = this;
  44032. action._prepare();
  44033. return action;
  44034. };
  44035. /**
  44036. * Process a specific trigger
  44037. * @param {number} trigger - the trigger to process
  44038. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44039. */
  44040. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44041. for (var index = 0; index < this.actions.length; index++) {
  44042. var action = this.actions[index];
  44043. if (action.trigger === trigger) {
  44044. if (evt) {
  44045. if (trigger === ActionManager.OnKeyUpTrigger
  44046. || trigger === ActionManager.OnKeyDownTrigger) {
  44047. var parameter = action.getTriggerParameter();
  44048. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44049. if (!parameter.toLowerCase) {
  44050. continue;
  44051. }
  44052. var lowerCase = parameter.toLowerCase();
  44053. if (lowerCase !== evt.sourceEvent.key) {
  44054. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44055. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44056. if (actualkey !== lowerCase) {
  44057. continue;
  44058. }
  44059. }
  44060. }
  44061. }
  44062. }
  44063. action._executeCurrent(evt);
  44064. }
  44065. }
  44066. };
  44067. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44068. var properties = propertyPath.split(".");
  44069. for (var index = 0; index < properties.length - 1; index++) {
  44070. target = target[properties[index]];
  44071. }
  44072. return target;
  44073. };
  44074. ActionManager.prototype._getProperty = function (propertyPath) {
  44075. var properties = propertyPath.split(".");
  44076. return properties[properties.length - 1];
  44077. };
  44078. ActionManager.prototype.serialize = function (name) {
  44079. var root = {
  44080. children: new Array(),
  44081. name: name,
  44082. type: 3,
  44083. properties: new Array() // Empty for root but required
  44084. };
  44085. for (var i = 0; i < this.actions.length; i++) {
  44086. var triggerObject = {
  44087. type: 0,
  44088. children: new Array(),
  44089. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44090. properties: new Array()
  44091. };
  44092. var triggerOptions = this.actions[i].triggerOptions;
  44093. if (triggerOptions && typeof triggerOptions !== "number") {
  44094. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44095. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44096. }
  44097. else {
  44098. var parameter = {};
  44099. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44100. if (triggerOptions.parameter.mesh) {
  44101. parameter._meshId = triggerOptions.parameter.mesh.id;
  44102. }
  44103. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44104. }
  44105. }
  44106. // Serialize child action, recursively
  44107. this.actions[i].serialize(triggerObject);
  44108. // Add serialized trigger
  44109. root.children.push(triggerObject);
  44110. }
  44111. return root;
  44112. };
  44113. ActionManager.Parse = function (parsedActions, object, scene) {
  44114. var actionManager = new ActionManager(scene);
  44115. if (object === null)
  44116. scene.actionManager = actionManager;
  44117. else
  44118. object.actionManager = actionManager;
  44119. // instanciate a new object
  44120. var instanciate = function (name, params) {
  44121. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44122. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44123. newInstance.constructor.apply(newInstance, params);
  44124. return newInstance;
  44125. };
  44126. var parseParameter = function (name, value, target, propertyPath) {
  44127. if (propertyPath === null) {
  44128. // String, boolean or float
  44129. var floatValue = parseFloat(value);
  44130. if (value === "true" || value === "false")
  44131. return value === "true";
  44132. else
  44133. return isNaN(floatValue) ? value : floatValue;
  44134. }
  44135. var effectiveTarget = propertyPath.split(".");
  44136. var values = value.split(",");
  44137. // Get effective Target
  44138. for (var i = 0; i < effectiveTarget.length; i++) {
  44139. target = target[effectiveTarget[i]];
  44140. }
  44141. // Return appropriate value with its type
  44142. if (typeof (target) === "boolean")
  44143. return values[0] === "true";
  44144. if (typeof (target) === "string")
  44145. return values[0];
  44146. // Parameters with multiple values such as Vector3 etc.
  44147. var split = new Array();
  44148. for (var i = 0; i < values.length; i++)
  44149. split.push(parseFloat(values[i]));
  44150. if (target instanceof BABYLON.Vector3)
  44151. return BABYLON.Vector3.FromArray(split);
  44152. if (target instanceof BABYLON.Vector4)
  44153. return BABYLON.Vector4.FromArray(split);
  44154. if (target instanceof BABYLON.Color3)
  44155. return BABYLON.Color3.FromArray(split);
  44156. if (target instanceof BABYLON.Color4)
  44157. return BABYLON.Color4.FromArray(split);
  44158. return parseFloat(values[0]);
  44159. };
  44160. // traverse graph per trigger
  44161. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44162. if (combineArray === void 0) { combineArray = null; }
  44163. if (parsedAction.detached)
  44164. return;
  44165. var parameters = new Array();
  44166. var target = null;
  44167. var propertyPath = null;
  44168. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44169. // Parameters
  44170. if (parsedAction.type === 2)
  44171. parameters.push(actionManager);
  44172. else
  44173. parameters.push(trigger);
  44174. if (combine) {
  44175. var actions = new Array();
  44176. for (var j = 0; j < parsedAction.combine.length; j++) {
  44177. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44178. }
  44179. parameters.push(actions);
  44180. }
  44181. else {
  44182. for (var i = 0; i < parsedAction.properties.length; i++) {
  44183. var value = parsedAction.properties[i].value;
  44184. var name = parsedAction.properties[i].name;
  44185. var targetType = parsedAction.properties[i].targetType;
  44186. if (name === "target")
  44187. if (targetType !== null && targetType === "SceneProperties")
  44188. value = target = scene;
  44189. else
  44190. value = target = scene.getNodeByName(value);
  44191. else if (name === "parent")
  44192. value = scene.getNodeByName(value);
  44193. else if (name === "sound")
  44194. value = scene.getSoundByName(value);
  44195. else if (name !== "propertyPath") {
  44196. if (parsedAction.type === 2 && name === "operator")
  44197. value = BABYLON.ValueCondition[value];
  44198. else
  44199. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44200. }
  44201. else {
  44202. propertyPath = value;
  44203. }
  44204. parameters.push(value);
  44205. }
  44206. }
  44207. if (combineArray === null) {
  44208. parameters.push(condition);
  44209. }
  44210. else {
  44211. parameters.push(null);
  44212. }
  44213. // If interpolate value action
  44214. if (parsedAction.name === "InterpolateValueAction") {
  44215. var param = parameters[parameters.length - 2];
  44216. parameters[parameters.length - 1] = param;
  44217. parameters[parameters.length - 2] = condition;
  44218. }
  44219. // Action or condition(s) and not CombineAction
  44220. var newAction = instanciate(parsedAction.name, parameters);
  44221. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44222. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44223. if (action)
  44224. action.then(nothing);
  44225. else
  44226. actionManager.registerAction(nothing);
  44227. action = nothing;
  44228. }
  44229. if (combineArray === null) {
  44230. if (newAction instanceof BABYLON.Condition) {
  44231. condition = newAction;
  44232. newAction = action;
  44233. }
  44234. else {
  44235. condition = null;
  44236. if (action)
  44237. action.then(newAction);
  44238. else
  44239. actionManager.registerAction(newAction);
  44240. }
  44241. }
  44242. else {
  44243. combineArray.push(newAction);
  44244. }
  44245. for (var i = 0; i < parsedAction.children.length; i++)
  44246. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44247. };
  44248. // triggers
  44249. for (var i = 0; i < parsedActions.children.length; i++) {
  44250. var triggerParams;
  44251. var trigger = parsedActions.children[i];
  44252. if (trigger.properties.length > 0) {
  44253. var param = trigger.properties[0].value;
  44254. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44255. if (value._meshId) {
  44256. value.mesh = scene.getMeshByID(value._meshId);
  44257. }
  44258. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44259. }
  44260. else
  44261. triggerParams = ActionManager[trigger.name];
  44262. for (var j = 0; j < trigger.children.length; j++) {
  44263. if (!trigger.detached)
  44264. traverse(trigger.children[j], triggerParams, null, null);
  44265. }
  44266. }
  44267. };
  44268. ActionManager.GetTriggerName = function (trigger) {
  44269. switch (trigger) {
  44270. case 0: return "NothingTrigger";
  44271. case 1: return "OnPickTrigger";
  44272. case 2: return "OnLeftPickTrigger";
  44273. case 3: return "OnRightPickTrigger";
  44274. case 4: return "OnCenterPickTrigger";
  44275. case 5: return "OnPickDownTrigger";
  44276. case 6: return "OnPickUpTrigger";
  44277. case 7: return "OnLongPressTrigger";
  44278. case 8: return "OnPointerOverTrigger";
  44279. case 9: return "OnPointerOutTrigger";
  44280. case 10: return "OnEveryFrameTrigger";
  44281. case 11: return "OnIntersectionEnterTrigger";
  44282. case 12: return "OnIntersectionExitTrigger";
  44283. case 13: return "OnKeyDownTrigger";
  44284. case 14: return "OnKeyUpTrigger";
  44285. case 15: return "OnPickOutTrigger";
  44286. default: return "";
  44287. }
  44288. };
  44289. // Statics
  44290. ActionManager._NothingTrigger = 0;
  44291. ActionManager._OnPickTrigger = 1;
  44292. ActionManager._OnLeftPickTrigger = 2;
  44293. ActionManager._OnRightPickTrigger = 3;
  44294. ActionManager._OnCenterPickTrigger = 4;
  44295. ActionManager._OnPickDownTrigger = 5;
  44296. ActionManager._OnDoublePickTrigger = 6;
  44297. ActionManager._OnPickUpTrigger = 7;
  44298. ActionManager._OnLongPressTrigger = 8;
  44299. ActionManager._OnPointerOverTrigger = 9;
  44300. ActionManager._OnPointerOutTrigger = 10;
  44301. ActionManager._OnEveryFrameTrigger = 11;
  44302. ActionManager._OnIntersectionEnterTrigger = 12;
  44303. ActionManager._OnIntersectionExitTrigger = 13;
  44304. ActionManager._OnKeyDownTrigger = 14;
  44305. ActionManager._OnKeyUpTrigger = 15;
  44306. ActionManager._OnPickOutTrigger = 16;
  44307. ActionManager.Triggers = {};
  44308. return ActionManager;
  44309. }());
  44310. BABYLON.ActionManager = ActionManager;
  44311. })(BABYLON || (BABYLON = {}));
  44312. //# sourceMappingURL=babylon.actionManager.js.map
  44313. var BABYLON;
  44314. (function (BABYLON) {
  44315. var InterpolateValueAction = /** @class */ (function (_super) {
  44316. __extends(InterpolateValueAction, _super);
  44317. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44318. if (duration === void 0) { duration = 1000; }
  44319. var _this = _super.call(this, triggerOptions, condition) || this;
  44320. _this.propertyPath = propertyPath;
  44321. _this.value = value;
  44322. _this.duration = duration;
  44323. _this.stopOtherAnimations = stopOtherAnimations;
  44324. _this.onInterpolationDone = onInterpolationDone;
  44325. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44326. _this._target = _this._effectiveTarget = target;
  44327. return _this;
  44328. }
  44329. InterpolateValueAction.prototype._prepare = function () {
  44330. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44331. this._property = this._getProperty(this.propertyPath);
  44332. };
  44333. InterpolateValueAction.prototype.execute = function () {
  44334. var _this = this;
  44335. var scene = this._actionManager.getScene();
  44336. var keys = [
  44337. {
  44338. frame: 0,
  44339. value: this._effectiveTarget[this._property]
  44340. }, {
  44341. frame: 100,
  44342. value: this.value
  44343. }
  44344. ];
  44345. var dataType;
  44346. if (typeof this.value === "number") {
  44347. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44348. }
  44349. else if (this.value instanceof BABYLON.Color3) {
  44350. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44351. }
  44352. else if (this.value instanceof BABYLON.Vector3) {
  44353. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44354. }
  44355. else if (this.value instanceof BABYLON.Matrix) {
  44356. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44357. }
  44358. else if (this.value instanceof BABYLON.Quaternion) {
  44359. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44360. }
  44361. else {
  44362. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44363. return;
  44364. }
  44365. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44366. animation.setKeys(keys);
  44367. if (this.stopOtherAnimations) {
  44368. scene.stopAnimation(this._effectiveTarget);
  44369. }
  44370. var wrapper = function () {
  44371. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44372. if (_this.onInterpolationDone) {
  44373. _this.onInterpolationDone();
  44374. }
  44375. };
  44376. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44377. };
  44378. InterpolateValueAction.prototype.serialize = function (parent) {
  44379. return _super.prototype._serialize.call(this, {
  44380. name: "InterpolateValueAction",
  44381. properties: [
  44382. BABYLON.Action._GetTargetProperty(this._target),
  44383. { name: "propertyPath", value: this.propertyPath },
  44384. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44385. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44386. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44387. ]
  44388. }, parent);
  44389. };
  44390. return InterpolateValueAction;
  44391. }(BABYLON.Action));
  44392. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44393. })(BABYLON || (BABYLON = {}));
  44394. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44395. var BABYLON;
  44396. (function (BABYLON) {
  44397. var SwitchBooleanAction = /** @class */ (function (_super) {
  44398. __extends(SwitchBooleanAction, _super);
  44399. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44400. var _this = _super.call(this, triggerOptions, condition) || this;
  44401. _this.propertyPath = propertyPath;
  44402. _this._target = _this._effectiveTarget = target;
  44403. return _this;
  44404. }
  44405. SwitchBooleanAction.prototype._prepare = function () {
  44406. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44407. this._property = this._getProperty(this.propertyPath);
  44408. };
  44409. SwitchBooleanAction.prototype.execute = function () {
  44410. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44411. };
  44412. SwitchBooleanAction.prototype.serialize = function (parent) {
  44413. return _super.prototype._serialize.call(this, {
  44414. name: "SwitchBooleanAction",
  44415. properties: [
  44416. BABYLON.Action._GetTargetProperty(this._target),
  44417. { name: "propertyPath", value: this.propertyPath }
  44418. ]
  44419. }, parent);
  44420. };
  44421. return SwitchBooleanAction;
  44422. }(BABYLON.Action));
  44423. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44424. var SetStateAction = /** @class */ (function (_super) {
  44425. __extends(SetStateAction, _super);
  44426. function SetStateAction(triggerOptions, target, value, condition) {
  44427. var _this = _super.call(this, triggerOptions, condition) || this;
  44428. _this.value = value;
  44429. _this._target = target;
  44430. return _this;
  44431. }
  44432. SetStateAction.prototype.execute = function () {
  44433. this._target.state = this.value;
  44434. };
  44435. SetStateAction.prototype.serialize = function (parent) {
  44436. return _super.prototype._serialize.call(this, {
  44437. name: "SetStateAction",
  44438. properties: [
  44439. BABYLON.Action._GetTargetProperty(this._target),
  44440. { name: "value", value: this.value }
  44441. ]
  44442. }, parent);
  44443. };
  44444. return SetStateAction;
  44445. }(BABYLON.Action));
  44446. BABYLON.SetStateAction = SetStateAction;
  44447. var SetValueAction = /** @class */ (function (_super) {
  44448. __extends(SetValueAction, _super);
  44449. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44450. var _this = _super.call(this, triggerOptions, condition) || this;
  44451. _this.propertyPath = propertyPath;
  44452. _this.value = value;
  44453. _this._target = _this._effectiveTarget = target;
  44454. return _this;
  44455. }
  44456. SetValueAction.prototype._prepare = function () {
  44457. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44458. this._property = this._getProperty(this.propertyPath);
  44459. };
  44460. SetValueAction.prototype.execute = function () {
  44461. this._effectiveTarget[this._property] = this.value;
  44462. if (this._target.markAsDirty) {
  44463. this._target.markAsDirty(this._property);
  44464. }
  44465. };
  44466. SetValueAction.prototype.serialize = function (parent) {
  44467. return _super.prototype._serialize.call(this, {
  44468. name: "SetValueAction",
  44469. properties: [
  44470. BABYLON.Action._GetTargetProperty(this._target),
  44471. { name: "propertyPath", value: this.propertyPath },
  44472. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44473. ]
  44474. }, parent);
  44475. };
  44476. return SetValueAction;
  44477. }(BABYLON.Action));
  44478. BABYLON.SetValueAction = SetValueAction;
  44479. var IncrementValueAction = /** @class */ (function (_super) {
  44480. __extends(IncrementValueAction, _super);
  44481. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44482. var _this = _super.call(this, triggerOptions, condition) || this;
  44483. _this.propertyPath = propertyPath;
  44484. _this.value = value;
  44485. _this._target = _this._effectiveTarget = target;
  44486. return _this;
  44487. }
  44488. IncrementValueAction.prototype._prepare = function () {
  44489. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44490. this._property = this._getProperty(this.propertyPath);
  44491. if (typeof this._effectiveTarget[this._property] !== "number") {
  44492. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44493. }
  44494. };
  44495. IncrementValueAction.prototype.execute = function () {
  44496. this._effectiveTarget[this._property] += this.value;
  44497. if (this._target.markAsDirty) {
  44498. this._target.markAsDirty(this._property);
  44499. }
  44500. };
  44501. IncrementValueAction.prototype.serialize = function (parent) {
  44502. return _super.prototype._serialize.call(this, {
  44503. name: "IncrementValueAction",
  44504. properties: [
  44505. BABYLON.Action._GetTargetProperty(this._target),
  44506. { name: "propertyPath", value: this.propertyPath },
  44507. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44508. ]
  44509. }, parent);
  44510. };
  44511. return IncrementValueAction;
  44512. }(BABYLON.Action));
  44513. BABYLON.IncrementValueAction = IncrementValueAction;
  44514. var PlayAnimationAction = /** @class */ (function (_super) {
  44515. __extends(PlayAnimationAction, _super);
  44516. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44517. var _this = _super.call(this, triggerOptions, condition) || this;
  44518. _this.from = from;
  44519. _this.to = to;
  44520. _this.loop = loop;
  44521. _this._target = target;
  44522. return _this;
  44523. }
  44524. PlayAnimationAction.prototype._prepare = function () {
  44525. };
  44526. PlayAnimationAction.prototype.execute = function () {
  44527. var scene = this._actionManager.getScene();
  44528. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44529. };
  44530. PlayAnimationAction.prototype.serialize = function (parent) {
  44531. return _super.prototype._serialize.call(this, {
  44532. name: "PlayAnimationAction",
  44533. properties: [
  44534. BABYLON.Action._GetTargetProperty(this._target),
  44535. { name: "from", value: String(this.from) },
  44536. { name: "to", value: String(this.to) },
  44537. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44538. ]
  44539. }, parent);
  44540. };
  44541. return PlayAnimationAction;
  44542. }(BABYLON.Action));
  44543. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44544. var StopAnimationAction = /** @class */ (function (_super) {
  44545. __extends(StopAnimationAction, _super);
  44546. function StopAnimationAction(triggerOptions, target, condition) {
  44547. var _this = _super.call(this, triggerOptions, condition) || this;
  44548. _this._target = target;
  44549. return _this;
  44550. }
  44551. StopAnimationAction.prototype._prepare = function () {
  44552. };
  44553. StopAnimationAction.prototype.execute = function () {
  44554. var scene = this._actionManager.getScene();
  44555. scene.stopAnimation(this._target);
  44556. };
  44557. StopAnimationAction.prototype.serialize = function (parent) {
  44558. return _super.prototype._serialize.call(this, {
  44559. name: "StopAnimationAction",
  44560. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44561. }, parent);
  44562. };
  44563. return StopAnimationAction;
  44564. }(BABYLON.Action));
  44565. BABYLON.StopAnimationAction = StopAnimationAction;
  44566. var DoNothingAction = /** @class */ (function (_super) {
  44567. __extends(DoNothingAction, _super);
  44568. function DoNothingAction(triggerOptions, condition) {
  44569. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44570. return _super.call(this, triggerOptions, condition) || this;
  44571. }
  44572. DoNothingAction.prototype.execute = function () {
  44573. };
  44574. DoNothingAction.prototype.serialize = function (parent) {
  44575. return _super.prototype._serialize.call(this, {
  44576. name: "DoNothingAction",
  44577. properties: []
  44578. }, parent);
  44579. };
  44580. return DoNothingAction;
  44581. }(BABYLON.Action));
  44582. BABYLON.DoNothingAction = DoNothingAction;
  44583. var CombineAction = /** @class */ (function (_super) {
  44584. __extends(CombineAction, _super);
  44585. function CombineAction(triggerOptions, children, condition) {
  44586. var _this = _super.call(this, triggerOptions, condition) || this;
  44587. _this.children = children;
  44588. return _this;
  44589. }
  44590. CombineAction.prototype._prepare = function () {
  44591. for (var index = 0; index < this.children.length; index++) {
  44592. this.children[index]._actionManager = this._actionManager;
  44593. this.children[index]._prepare();
  44594. }
  44595. };
  44596. CombineAction.prototype.execute = function (evt) {
  44597. for (var index = 0; index < this.children.length; index++) {
  44598. this.children[index].execute(evt);
  44599. }
  44600. };
  44601. CombineAction.prototype.serialize = function (parent) {
  44602. var serializationObject = _super.prototype._serialize.call(this, {
  44603. name: "CombineAction",
  44604. properties: [],
  44605. combine: []
  44606. }, parent);
  44607. for (var i = 0; i < this.children.length; i++) {
  44608. serializationObject.combine.push(this.children[i].serialize(null));
  44609. }
  44610. return serializationObject;
  44611. };
  44612. return CombineAction;
  44613. }(BABYLON.Action));
  44614. BABYLON.CombineAction = CombineAction;
  44615. var ExecuteCodeAction = /** @class */ (function (_super) {
  44616. __extends(ExecuteCodeAction, _super);
  44617. function ExecuteCodeAction(triggerOptions, func, condition) {
  44618. var _this = _super.call(this, triggerOptions, condition) || this;
  44619. _this.func = func;
  44620. return _this;
  44621. }
  44622. ExecuteCodeAction.prototype.execute = function (evt) {
  44623. this.func(evt);
  44624. };
  44625. return ExecuteCodeAction;
  44626. }(BABYLON.Action));
  44627. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44628. var SetParentAction = /** @class */ (function (_super) {
  44629. __extends(SetParentAction, _super);
  44630. function SetParentAction(triggerOptions, target, parent, condition) {
  44631. var _this = _super.call(this, triggerOptions, condition) || this;
  44632. _this._target = target;
  44633. _this._parent = parent;
  44634. return _this;
  44635. }
  44636. SetParentAction.prototype._prepare = function () {
  44637. };
  44638. SetParentAction.prototype.execute = function () {
  44639. if (this._target.parent === this._parent) {
  44640. return;
  44641. }
  44642. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44643. invertParentWorldMatrix.invert();
  44644. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44645. this._target.parent = this._parent;
  44646. };
  44647. SetParentAction.prototype.serialize = function (parent) {
  44648. return _super.prototype._serialize.call(this, {
  44649. name: "SetParentAction",
  44650. properties: [
  44651. BABYLON.Action._GetTargetProperty(this._target),
  44652. BABYLON.Action._GetTargetProperty(this._parent),
  44653. ]
  44654. }, parent);
  44655. };
  44656. return SetParentAction;
  44657. }(BABYLON.Action));
  44658. BABYLON.SetParentAction = SetParentAction;
  44659. var PlaySoundAction = /** @class */ (function (_super) {
  44660. __extends(PlaySoundAction, _super);
  44661. function PlaySoundAction(triggerOptions, sound, condition) {
  44662. var _this = _super.call(this, triggerOptions, condition) || this;
  44663. _this._sound = sound;
  44664. return _this;
  44665. }
  44666. PlaySoundAction.prototype._prepare = function () {
  44667. };
  44668. PlaySoundAction.prototype.execute = function () {
  44669. if (this._sound !== undefined)
  44670. this._sound.play();
  44671. };
  44672. PlaySoundAction.prototype.serialize = function (parent) {
  44673. return _super.prototype._serialize.call(this, {
  44674. name: "PlaySoundAction",
  44675. properties: [{ name: "sound", value: this._sound.name }]
  44676. }, parent);
  44677. };
  44678. return PlaySoundAction;
  44679. }(BABYLON.Action));
  44680. BABYLON.PlaySoundAction = PlaySoundAction;
  44681. var StopSoundAction = /** @class */ (function (_super) {
  44682. __extends(StopSoundAction, _super);
  44683. function StopSoundAction(triggerOptions, sound, condition) {
  44684. var _this = _super.call(this, triggerOptions, condition) || this;
  44685. _this._sound = sound;
  44686. return _this;
  44687. }
  44688. StopSoundAction.prototype._prepare = function () {
  44689. };
  44690. StopSoundAction.prototype.execute = function () {
  44691. if (this._sound !== undefined)
  44692. this._sound.stop();
  44693. };
  44694. StopSoundAction.prototype.serialize = function (parent) {
  44695. return _super.prototype._serialize.call(this, {
  44696. name: "StopSoundAction",
  44697. properties: [{ name: "sound", value: this._sound.name }]
  44698. }, parent);
  44699. };
  44700. return StopSoundAction;
  44701. }(BABYLON.Action));
  44702. BABYLON.StopSoundAction = StopSoundAction;
  44703. })(BABYLON || (BABYLON = {}));
  44704. //# sourceMappingURL=babylon.directActions.js.map
  44705. var BABYLON;
  44706. (function (BABYLON) {
  44707. var SpriteManager = /** @class */ (function () {
  44708. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44709. if (epsilon === void 0) { epsilon = 0.01; }
  44710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44711. this.name = name;
  44712. this.sprites = new Array();
  44713. this.renderingGroupId = 0;
  44714. this.layerMask = 0x0FFFFFFF;
  44715. this.fogEnabled = true;
  44716. this.isPickable = false;
  44717. /**
  44718. * An event triggered when the manager is disposed.
  44719. * @type {BABYLON.Observable}
  44720. */
  44721. this.onDisposeObservable = new BABYLON.Observable();
  44722. this._vertexBuffers = {};
  44723. this._capacity = capacity;
  44724. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44725. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44726. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44727. if (cellSize.width && cellSize.height) {
  44728. this.cellWidth = cellSize.width;
  44729. this.cellHeight = cellSize.height;
  44730. }
  44731. else if (cellSize !== undefined) {
  44732. this.cellWidth = cellSize;
  44733. this.cellHeight = cellSize;
  44734. }
  44735. else {
  44736. return;
  44737. }
  44738. this._epsilon = epsilon;
  44739. this._scene = scene;
  44740. this._scene.spriteManagers.push(this);
  44741. var indices = [];
  44742. var index = 0;
  44743. for (var count = 0; count < capacity; count++) {
  44744. indices.push(index);
  44745. indices.push(index + 1);
  44746. indices.push(index + 2);
  44747. indices.push(index);
  44748. indices.push(index + 2);
  44749. indices.push(index + 3);
  44750. index += 4;
  44751. }
  44752. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44753. // VBO
  44754. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44755. this._vertexData = new Float32Array(capacity * 16 * 4);
  44756. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44757. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44758. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44759. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44760. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44762. this._vertexBuffers["options"] = options;
  44763. this._vertexBuffers["cellInfo"] = cellInfo;
  44764. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44765. // Effects
  44766. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44767. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44768. }
  44769. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44770. set: function (callback) {
  44771. if (this._onDisposeObserver) {
  44772. this.onDisposeObservable.remove(this._onDisposeObserver);
  44773. }
  44774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44775. },
  44776. enumerable: true,
  44777. configurable: true
  44778. });
  44779. Object.defineProperty(SpriteManager.prototype, "texture", {
  44780. get: function () {
  44781. return this._spriteTexture;
  44782. },
  44783. set: function (value) {
  44784. this._spriteTexture = value;
  44785. },
  44786. enumerable: true,
  44787. configurable: true
  44788. });
  44789. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44790. var arrayOffset = index * 16;
  44791. if (offsetX === 0)
  44792. offsetX = this._epsilon;
  44793. else if (offsetX === 1)
  44794. offsetX = 1 - this._epsilon;
  44795. if (offsetY === 0)
  44796. offsetY = this._epsilon;
  44797. else if (offsetY === 1)
  44798. offsetY = 1 - this._epsilon;
  44799. this._vertexData[arrayOffset] = sprite.position.x;
  44800. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44801. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44802. this._vertexData[arrayOffset + 3] = sprite.angle;
  44803. this._vertexData[arrayOffset + 4] = sprite.width;
  44804. this._vertexData[arrayOffset + 5] = sprite.height;
  44805. this._vertexData[arrayOffset + 6] = offsetX;
  44806. this._vertexData[arrayOffset + 7] = offsetY;
  44807. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44808. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44809. var offset = (sprite.cellIndex / rowSize) >> 0;
  44810. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44811. this._vertexData[arrayOffset + 11] = offset;
  44812. // Color
  44813. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44814. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44815. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44816. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44817. };
  44818. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44819. var count = Math.min(this._capacity, this.sprites.length);
  44820. var min = BABYLON.Vector3.Zero();
  44821. var max = BABYLON.Vector3.Zero();
  44822. var distance = Number.MAX_VALUE;
  44823. var currentSprite = null;
  44824. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44825. var cameraView = camera.getViewMatrix();
  44826. for (var index = 0; index < count; index++) {
  44827. var sprite = this.sprites[index];
  44828. if (!sprite) {
  44829. continue;
  44830. }
  44831. if (predicate) {
  44832. if (!predicate(sprite)) {
  44833. continue;
  44834. }
  44835. }
  44836. else if (!sprite.isPickable) {
  44837. continue;
  44838. }
  44839. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44840. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44841. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44842. if (ray.intersectsBoxMinMax(min, max)) {
  44843. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44844. if (distance > currentDistance) {
  44845. distance = currentDistance;
  44846. currentSprite = sprite;
  44847. if (fastCheck) {
  44848. break;
  44849. }
  44850. }
  44851. }
  44852. }
  44853. if (currentSprite) {
  44854. var result = new BABYLON.PickingInfo();
  44855. result.hit = true;
  44856. result.pickedSprite = currentSprite;
  44857. result.distance = distance;
  44858. return result;
  44859. }
  44860. return null;
  44861. };
  44862. SpriteManager.prototype.render = function () {
  44863. // Check
  44864. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44865. return;
  44866. var engine = this._scene.getEngine();
  44867. var baseSize = this._spriteTexture.getBaseSize();
  44868. // Sprites
  44869. var deltaTime = engine.getDeltaTime();
  44870. var max = Math.min(this._capacity, this.sprites.length);
  44871. var rowSize = baseSize.width / this.cellWidth;
  44872. var offset = 0;
  44873. for (var index = 0; index < max; index++) {
  44874. var sprite = this.sprites[index];
  44875. if (!sprite) {
  44876. continue;
  44877. }
  44878. sprite._animate(deltaTime);
  44879. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44880. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44881. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44882. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44883. }
  44884. this._buffer.update(this._vertexData);
  44885. // Render
  44886. var effect = this._effectBase;
  44887. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44888. effect = this._effectFog;
  44889. }
  44890. engine.enableEffect(effect);
  44891. var viewMatrix = this._scene.getViewMatrix();
  44892. effect.setTexture("diffuseSampler", this._spriteTexture);
  44893. effect.setMatrix("view", viewMatrix);
  44894. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44895. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44896. // Fog
  44897. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44898. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44899. effect.setColor3("vFogColor", this._scene.fogColor);
  44900. }
  44901. // VBOs
  44902. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44903. // Draw order
  44904. engine.setDepthFunctionToLessOrEqual();
  44905. effect.setBool("alphaTest", true);
  44906. engine.setColorWrite(false);
  44907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44908. engine.setColorWrite(true);
  44909. effect.setBool("alphaTest", false);
  44910. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44911. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44912. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44913. };
  44914. SpriteManager.prototype.dispose = function () {
  44915. if (this._buffer) {
  44916. this._buffer.dispose();
  44917. this._buffer = null;
  44918. }
  44919. if (this._indexBuffer) {
  44920. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44921. this._indexBuffer = null;
  44922. }
  44923. if (this._spriteTexture) {
  44924. this._spriteTexture.dispose();
  44925. this._spriteTexture = null;
  44926. }
  44927. // Remove from scene
  44928. var index = this._scene.spriteManagers.indexOf(this);
  44929. this._scene.spriteManagers.splice(index, 1);
  44930. // Callback
  44931. this.onDisposeObservable.notifyObservers(this);
  44932. this.onDisposeObservable.clear();
  44933. };
  44934. return SpriteManager;
  44935. }());
  44936. BABYLON.SpriteManager = SpriteManager;
  44937. })(BABYLON || (BABYLON = {}));
  44938. //# sourceMappingURL=babylon.spriteManager.js.map
  44939. var BABYLON;
  44940. (function (BABYLON) {
  44941. var Sprite = /** @class */ (function () {
  44942. function Sprite(name, manager) {
  44943. this.name = name;
  44944. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44945. this.width = 1.0;
  44946. this.height = 1.0;
  44947. this.angle = 0;
  44948. this.cellIndex = 0;
  44949. this.invertU = 0;
  44950. this.invertV = 0;
  44951. this.animations = new Array();
  44952. this.isPickable = false;
  44953. this._animationStarted = false;
  44954. this._loopAnimation = false;
  44955. this._fromIndex = 0;
  44956. this._toIndex = 0;
  44957. this._delay = 0;
  44958. this._direction = 1;
  44959. this._time = 0;
  44960. this._manager = manager;
  44961. this._manager.sprites.push(this);
  44962. this.position = BABYLON.Vector3.Zero();
  44963. }
  44964. Object.defineProperty(Sprite.prototype, "size", {
  44965. get: function () {
  44966. return this.width;
  44967. },
  44968. set: function (value) {
  44969. this.width = value;
  44970. this.height = value;
  44971. },
  44972. enumerable: true,
  44973. configurable: true
  44974. });
  44975. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44976. this._fromIndex = from;
  44977. this._toIndex = to;
  44978. this._loopAnimation = loop;
  44979. this._delay = delay;
  44980. this._animationStarted = true;
  44981. this._direction = from < to ? 1 : -1;
  44982. this.cellIndex = from;
  44983. this._time = 0;
  44984. this._onAnimationEnd = onAnimationEnd;
  44985. };
  44986. Sprite.prototype.stopAnimation = function () {
  44987. this._animationStarted = false;
  44988. };
  44989. Sprite.prototype._animate = function (deltaTime) {
  44990. if (!this._animationStarted)
  44991. return;
  44992. this._time += deltaTime;
  44993. if (this._time > this._delay) {
  44994. this._time = this._time % this._delay;
  44995. this.cellIndex += this._direction;
  44996. if (this.cellIndex > this._toIndex) {
  44997. if (this._loopAnimation) {
  44998. this.cellIndex = this._fromIndex;
  44999. }
  45000. else {
  45001. this.cellIndex = this._toIndex;
  45002. this._animationStarted = false;
  45003. if (this._onAnimationEnd) {
  45004. this._onAnimationEnd();
  45005. }
  45006. if (this.disposeWhenFinishedAnimating) {
  45007. this.dispose();
  45008. }
  45009. }
  45010. }
  45011. }
  45012. };
  45013. Sprite.prototype.dispose = function () {
  45014. for (var i = 0; i < this._manager.sprites.length; i++) {
  45015. if (this._manager.sprites[i] == this) {
  45016. this._manager.sprites.splice(i, 1);
  45017. }
  45018. }
  45019. };
  45020. return Sprite;
  45021. }());
  45022. BABYLON.Sprite = Sprite;
  45023. })(BABYLON || (BABYLON = {}));
  45024. //# sourceMappingURL=babylon.sprite.js.map
  45025. var BABYLON;
  45026. (function (BABYLON) {
  45027. var IntersectionInfo = /** @class */ (function () {
  45028. function IntersectionInfo(bu, bv, distance) {
  45029. this.bu = bu;
  45030. this.bv = bv;
  45031. this.distance = distance;
  45032. this.faceId = 0;
  45033. this.subMeshId = 0;
  45034. }
  45035. return IntersectionInfo;
  45036. }());
  45037. BABYLON.IntersectionInfo = IntersectionInfo;
  45038. var PickingInfo = /** @class */ (function () {
  45039. function PickingInfo() {
  45040. this.hit = false;
  45041. this.distance = 0;
  45042. this.pickedPoint = null;
  45043. this.pickedMesh = null;
  45044. this.bu = 0;
  45045. this.bv = 0;
  45046. this.faceId = -1;
  45047. this.subMeshId = 0;
  45048. this.pickedSprite = null;
  45049. }
  45050. // Methods
  45051. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45052. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45053. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45054. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45055. return null;
  45056. }
  45057. var indices = this.pickedMesh.getIndices();
  45058. if (!indices) {
  45059. return null;
  45060. }
  45061. var result;
  45062. if (useVerticesNormals) {
  45063. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45064. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45065. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45066. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45067. normal0 = normal0.scale(this.bu);
  45068. normal1 = normal1.scale(this.bv);
  45069. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45070. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45071. }
  45072. else {
  45073. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45074. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45075. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45076. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45077. var p1p2 = vertex1.subtract(vertex2);
  45078. var p3p2 = vertex3.subtract(vertex2);
  45079. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45080. }
  45081. if (useWorldCoordinates) {
  45082. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45083. }
  45084. return BABYLON.Vector3.Normalize(result);
  45085. };
  45086. PickingInfo.prototype.getTextureCoordinates = function () {
  45087. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45088. return null;
  45089. }
  45090. var indices = this.pickedMesh.getIndices();
  45091. if (!indices) {
  45092. return null;
  45093. }
  45094. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45095. if (!uvs) {
  45096. return null;
  45097. }
  45098. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45099. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45100. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45101. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45102. uv1 = uv1.scale(this.bu);
  45103. uv2 = uv2.scale(this.bv);
  45104. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45105. };
  45106. return PickingInfo;
  45107. }());
  45108. BABYLON.PickingInfo = PickingInfo;
  45109. })(BABYLON || (BABYLON = {}));
  45110. //# sourceMappingURL=babylon.pickingInfo.js.map
  45111. var BABYLON;
  45112. (function (BABYLON) {
  45113. var Ray = /** @class */ (function () {
  45114. function Ray(origin, direction, length) {
  45115. if (length === void 0) { length = Number.MAX_VALUE; }
  45116. this.origin = origin;
  45117. this.direction = direction;
  45118. this.length = length;
  45119. }
  45120. // Methods
  45121. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45122. var d = 0.0;
  45123. var maxValue = Number.MAX_VALUE;
  45124. var inv;
  45125. var min;
  45126. var max;
  45127. var temp;
  45128. if (Math.abs(this.direction.x) < 0.0000001) {
  45129. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45130. return false;
  45131. }
  45132. }
  45133. else {
  45134. inv = 1.0 / this.direction.x;
  45135. min = (minimum.x - this.origin.x) * inv;
  45136. max = (maximum.x - this.origin.x) * inv;
  45137. if (max === -Infinity) {
  45138. max = Infinity;
  45139. }
  45140. if (min > max) {
  45141. temp = min;
  45142. min = max;
  45143. max = temp;
  45144. }
  45145. d = Math.max(min, d);
  45146. maxValue = Math.min(max, maxValue);
  45147. if (d > maxValue) {
  45148. return false;
  45149. }
  45150. }
  45151. if (Math.abs(this.direction.y) < 0.0000001) {
  45152. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45153. return false;
  45154. }
  45155. }
  45156. else {
  45157. inv = 1.0 / this.direction.y;
  45158. min = (minimum.y - this.origin.y) * inv;
  45159. max = (maximum.y - this.origin.y) * inv;
  45160. if (max === -Infinity) {
  45161. max = Infinity;
  45162. }
  45163. if (min > max) {
  45164. temp = min;
  45165. min = max;
  45166. max = temp;
  45167. }
  45168. d = Math.max(min, d);
  45169. maxValue = Math.min(max, maxValue);
  45170. if (d > maxValue) {
  45171. return false;
  45172. }
  45173. }
  45174. if (Math.abs(this.direction.z) < 0.0000001) {
  45175. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45176. return false;
  45177. }
  45178. }
  45179. else {
  45180. inv = 1.0 / this.direction.z;
  45181. min = (minimum.z - this.origin.z) * inv;
  45182. max = (maximum.z - this.origin.z) * inv;
  45183. if (max === -Infinity) {
  45184. max = Infinity;
  45185. }
  45186. if (min > max) {
  45187. temp = min;
  45188. min = max;
  45189. max = temp;
  45190. }
  45191. d = Math.max(min, d);
  45192. maxValue = Math.min(max, maxValue);
  45193. if (d > maxValue) {
  45194. return false;
  45195. }
  45196. }
  45197. return true;
  45198. };
  45199. Ray.prototype.intersectsBox = function (box) {
  45200. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45201. };
  45202. Ray.prototype.intersectsSphere = function (sphere) {
  45203. var x = sphere.center.x - this.origin.x;
  45204. var y = sphere.center.y - this.origin.y;
  45205. var z = sphere.center.z - this.origin.z;
  45206. var pyth = (x * x) + (y * y) + (z * z);
  45207. var rr = sphere.radius * sphere.radius;
  45208. if (pyth <= rr) {
  45209. return true;
  45210. }
  45211. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45212. if (dot < 0.0) {
  45213. return false;
  45214. }
  45215. var temp = pyth - (dot * dot);
  45216. return temp <= rr;
  45217. };
  45218. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45219. if (!this._edge1) {
  45220. this._edge1 = BABYLON.Vector3.Zero();
  45221. this._edge2 = BABYLON.Vector3.Zero();
  45222. this._pvec = BABYLON.Vector3.Zero();
  45223. this._tvec = BABYLON.Vector3.Zero();
  45224. this._qvec = BABYLON.Vector3.Zero();
  45225. }
  45226. vertex1.subtractToRef(vertex0, this._edge1);
  45227. vertex2.subtractToRef(vertex0, this._edge2);
  45228. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45229. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45230. if (det === 0) {
  45231. return null;
  45232. }
  45233. var invdet = 1 / det;
  45234. this.origin.subtractToRef(vertex0, this._tvec);
  45235. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45236. if (bu < 0 || bu > 1.0) {
  45237. return null;
  45238. }
  45239. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45240. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45241. if (bv < 0 || bu + bv > 1.0) {
  45242. return null;
  45243. }
  45244. //check if the distance is longer than the predefined length.
  45245. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45246. if (distance > this.length) {
  45247. return null;
  45248. }
  45249. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45250. };
  45251. Ray.prototype.intersectsPlane = function (plane) {
  45252. var distance;
  45253. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45254. if (Math.abs(result1) < 9.99999997475243E-07) {
  45255. return null;
  45256. }
  45257. else {
  45258. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45259. distance = (-plane.d - result2) / result1;
  45260. if (distance < 0.0) {
  45261. if (distance < -9.99999997475243E-07) {
  45262. return null;
  45263. }
  45264. else {
  45265. return 0;
  45266. }
  45267. }
  45268. return distance;
  45269. }
  45270. };
  45271. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45272. var tm = BABYLON.Tmp.Matrix[0];
  45273. mesh.getWorldMatrix().invertToRef(tm);
  45274. if (this._tmpRay) {
  45275. Ray.TransformToRef(this, tm, this._tmpRay);
  45276. }
  45277. else {
  45278. this._tmpRay = Ray.Transform(this, tm);
  45279. }
  45280. return mesh.intersects(this._tmpRay, fastCheck);
  45281. };
  45282. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45283. if (results) {
  45284. results.length = 0;
  45285. }
  45286. else {
  45287. results = [];
  45288. }
  45289. for (var i = 0; i < meshes.length; i++) {
  45290. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45291. if (pickInfo.hit) {
  45292. results.push(pickInfo);
  45293. }
  45294. }
  45295. results.sort(this._comparePickingInfo);
  45296. return results;
  45297. };
  45298. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45299. if (pickingInfoA.distance < pickingInfoB.distance) {
  45300. return -1;
  45301. }
  45302. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45303. return 1;
  45304. }
  45305. else {
  45306. return 0;
  45307. }
  45308. };
  45309. /**
  45310. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45311. * @param sega the first point of the segment to test the intersection against
  45312. * @param segb the second point of the segment to test the intersection against
  45313. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45314. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45315. */
  45316. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45317. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45318. var u = segb.subtract(sega);
  45319. var v = rsegb.subtract(this.origin);
  45320. var w = sega.subtract(this.origin);
  45321. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45322. var b = BABYLON.Vector3.Dot(u, v);
  45323. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45324. var d = BABYLON.Vector3.Dot(u, w);
  45325. var e = BABYLON.Vector3.Dot(v, w);
  45326. var D = a * c - b * b; // always >= 0
  45327. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45328. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45329. // compute the line parameters of the two closest points
  45330. if (D < Ray.smallnum) {
  45331. sN = 0.0; // force using point P0 on segment S1
  45332. sD = 1.0; // to prevent possible division by 0.0 later
  45333. tN = e;
  45334. tD = c;
  45335. }
  45336. else {
  45337. sN = (b * e - c * d);
  45338. tN = (a * e - b * d);
  45339. if (sN < 0.0) {
  45340. sN = 0.0;
  45341. tN = e;
  45342. tD = c;
  45343. }
  45344. else if (sN > sD) {
  45345. sN = sD;
  45346. tN = e + b;
  45347. tD = c;
  45348. }
  45349. }
  45350. if (tN < 0.0) {
  45351. tN = 0.0;
  45352. // recompute sc for this edge
  45353. if (-d < 0.0) {
  45354. sN = 0.0;
  45355. }
  45356. else if (-d > a)
  45357. sN = sD;
  45358. else {
  45359. sN = -d;
  45360. sD = a;
  45361. }
  45362. }
  45363. else if (tN > tD) {
  45364. tN = tD;
  45365. // recompute sc for this edge
  45366. if ((-d + b) < 0.0) {
  45367. sN = 0;
  45368. }
  45369. else if ((-d + b) > a) {
  45370. sN = sD;
  45371. }
  45372. else {
  45373. sN = (-d + b);
  45374. sD = a;
  45375. }
  45376. }
  45377. // finally do the division to get sc and tc
  45378. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45379. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45380. // get the difference of the two closest points
  45381. var qtc = v.multiplyByFloats(tc, tc, tc);
  45382. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45383. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45384. if (isIntersected) {
  45385. return qtc.length();
  45386. }
  45387. return -1;
  45388. };
  45389. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45390. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45391. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45392. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45393. this.direction.normalize();
  45394. return this;
  45395. };
  45396. // Statics
  45397. Ray.Zero = function () {
  45398. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45399. };
  45400. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45401. var result = Ray.Zero();
  45402. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45403. };
  45404. /**
  45405. * 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
  45406. * transformed to the given world matrix.
  45407. * @param origin The origin point
  45408. * @param end The end point
  45409. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45410. */
  45411. Ray.CreateNewFromTo = function (origin, end, world) {
  45412. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45413. var direction = end.subtract(origin);
  45414. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45415. direction.normalize();
  45416. return Ray.Transform(new Ray(origin, direction, length), world);
  45417. };
  45418. Ray.Transform = function (ray, matrix) {
  45419. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45420. Ray.TransformToRef(ray, matrix, result);
  45421. return result;
  45422. };
  45423. Ray.TransformToRef = function (ray, matrix, result) {
  45424. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45425. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45426. result.length = ray.length;
  45427. var dir = result.direction;
  45428. var len = dir.length();
  45429. if (!(len === 0 || len === 1)) {
  45430. var num = 1.0 / len;
  45431. dir.x *= num;
  45432. dir.y *= num;
  45433. dir.z *= num;
  45434. result.length *= len;
  45435. }
  45436. };
  45437. Ray.smallnum = 0.00000001;
  45438. Ray.rayl = 10e8;
  45439. return Ray;
  45440. }());
  45441. BABYLON.Ray = Ray;
  45442. })(BABYLON || (BABYLON = {}));
  45443. //# sourceMappingURL=babylon.ray.js.map
  45444. var BABYLON;
  45445. (function (BABYLON) {
  45446. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45447. if (boxMin.x > sphereCenter.x + sphereRadius)
  45448. return false;
  45449. if (sphereCenter.x - sphereRadius > boxMax.x)
  45450. return false;
  45451. if (boxMin.y > sphereCenter.y + sphereRadius)
  45452. return false;
  45453. if (sphereCenter.y - sphereRadius > boxMax.y)
  45454. return false;
  45455. if (boxMin.z > sphereCenter.z + sphereRadius)
  45456. return false;
  45457. if (sphereCenter.z - sphereRadius > boxMax.z)
  45458. return false;
  45459. return true;
  45460. };
  45461. var getLowestRoot = (function () {
  45462. var result = { root: 0, found: false };
  45463. return function (a, b, c, maxR) {
  45464. result.root = 0;
  45465. result.found = false;
  45466. var determinant = b * b - 4.0 * a * c;
  45467. if (determinant < 0)
  45468. return result;
  45469. var sqrtD = Math.sqrt(determinant);
  45470. var r1 = (-b - sqrtD) / (2.0 * a);
  45471. var r2 = (-b + sqrtD) / (2.0 * a);
  45472. if (r1 > r2) {
  45473. var temp = r2;
  45474. r2 = r1;
  45475. r1 = temp;
  45476. }
  45477. if (r1 > 0 && r1 < maxR) {
  45478. result.root = r1;
  45479. result.found = true;
  45480. return result;
  45481. }
  45482. if (r2 > 0 && r2 < maxR) {
  45483. result.root = r2;
  45484. result.found = true;
  45485. return result;
  45486. }
  45487. return result;
  45488. };
  45489. })();
  45490. var Collider = /** @class */ (function () {
  45491. function Collider() {
  45492. this._collisionPoint = BABYLON.Vector3.Zero();
  45493. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45494. this._tempVector = BABYLON.Vector3.Zero();
  45495. this._tempVector2 = BABYLON.Vector3.Zero();
  45496. this._tempVector3 = BABYLON.Vector3.Zero();
  45497. this._tempVector4 = BABYLON.Vector3.Zero();
  45498. this._edge = BABYLON.Vector3.Zero();
  45499. this._baseToVertex = BABYLON.Vector3.Zero();
  45500. this._destinationPoint = BABYLON.Vector3.Zero();
  45501. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45502. this._displacementVector = BABYLON.Vector3.Zero();
  45503. this._radius = BABYLON.Vector3.One();
  45504. this._retry = 0;
  45505. this._basePointWorld = BABYLON.Vector3.Zero();
  45506. this._velocityWorld = BABYLON.Vector3.Zero();
  45507. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45508. this._collisionMask = -1;
  45509. }
  45510. Object.defineProperty(Collider.prototype, "collisionMask", {
  45511. get: function () {
  45512. return this._collisionMask;
  45513. },
  45514. set: function (mask) {
  45515. this._collisionMask = !isNaN(mask) ? mask : -1;
  45516. },
  45517. enumerable: true,
  45518. configurable: true
  45519. });
  45520. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45521. /**
  45522. * Gets the plane normal used to compute the sliding response (in local space)
  45523. */
  45524. get: function () {
  45525. return this._slidePlaneNormal;
  45526. },
  45527. enumerable: true,
  45528. configurable: true
  45529. });
  45530. // Methods
  45531. Collider.prototype._initialize = function (source, dir, e) {
  45532. this._velocity = dir;
  45533. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45534. this._basePoint = source;
  45535. source.multiplyToRef(this._radius, this._basePointWorld);
  45536. dir.multiplyToRef(this._radius, this._velocityWorld);
  45537. this._velocityWorldLength = this._velocityWorld.length();
  45538. this._epsilon = e;
  45539. this.collisionFound = false;
  45540. };
  45541. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45542. pa.subtractToRef(point, this._tempVector);
  45543. pb.subtractToRef(point, this._tempVector2);
  45544. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45545. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45546. if (d < 0)
  45547. return false;
  45548. pc.subtractToRef(point, this._tempVector3);
  45549. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45550. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45551. if (d < 0)
  45552. return false;
  45553. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45554. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45555. return d >= 0;
  45556. };
  45557. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45558. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45559. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45560. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45561. return false;
  45562. }
  45563. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45564. return false;
  45565. return true;
  45566. };
  45567. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45568. var t0;
  45569. var embeddedInPlane = false;
  45570. //defensive programming, actually not needed.
  45571. if (!trianglePlaneArray) {
  45572. trianglePlaneArray = [];
  45573. }
  45574. if (!trianglePlaneArray[faceIndex]) {
  45575. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45576. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45577. }
  45578. var trianglePlane = trianglePlaneArray[faceIndex];
  45579. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45580. return;
  45581. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45582. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45583. if (normalDotVelocity == 0) {
  45584. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45585. return;
  45586. embeddedInPlane = true;
  45587. t0 = 0;
  45588. }
  45589. else {
  45590. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45591. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45592. if (t0 > t1) {
  45593. var temp = t1;
  45594. t1 = t0;
  45595. t0 = temp;
  45596. }
  45597. if (t0 > 1.0 || t1 < 0.0)
  45598. return;
  45599. if (t0 < 0)
  45600. t0 = 0;
  45601. if (t0 > 1.0)
  45602. t0 = 1.0;
  45603. }
  45604. this._collisionPoint.copyFromFloats(0, 0, 0);
  45605. var found = false;
  45606. var t = 1.0;
  45607. if (!embeddedInPlane) {
  45608. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45609. this._velocity.scaleToRef(t0, this._tempVector);
  45610. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45611. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45612. found = true;
  45613. t = t0;
  45614. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45615. }
  45616. }
  45617. if (!found) {
  45618. var velocitySquaredLength = this._velocity.lengthSquared();
  45619. var a = velocitySquaredLength;
  45620. this._basePoint.subtractToRef(p1, this._tempVector);
  45621. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45622. var c = this._tempVector.lengthSquared() - 1.0;
  45623. var lowestRoot = getLowestRoot(a, b, c, t);
  45624. if (lowestRoot.found) {
  45625. t = lowestRoot.root;
  45626. found = true;
  45627. this._collisionPoint.copyFrom(p1);
  45628. }
  45629. this._basePoint.subtractToRef(p2, this._tempVector);
  45630. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45631. c = this._tempVector.lengthSquared() - 1.0;
  45632. lowestRoot = getLowestRoot(a, b, c, t);
  45633. if (lowestRoot.found) {
  45634. t = lowestRoot.root;
  45635. found = true;
  45636. this._collisionPoint.copyFrom(p2);
  45637. }
  45638. this._basePoint.subtractToRef(p3, this._tempVector);
  45639. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45640. c = this._tempVector.lengthSquared() - 1.0;
  45641. lowestRoot = getLowestRoot(a, b, c, t);
  45642. if (lowestRoot.found) {
  45643. t = lowestRoot.root;
  45644. found = true;
  45645. this._collisionPoint.copyFrom(p3);
  45646. }
  45647. p2.subtractToRef(p1, this._edge);
  45648. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45649. var edgeSquaredLength = this._edge.lengthSquared();
  45650. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45651. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45652. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45653. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45654. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45655. lowestRoot = getLowestRoot(a, b, c, t);
  45656. if (lowestRoot.found) {
  45657. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45658. if (f >= 0.0 && f <= 1.0) {
  45659. t = lowestRoot.root;
  45660. found = true;
  45661. this._edge.scaleInPlace(f);
  45662. p1.addToRef(this._edge, this._collisionPoint);
  45663. }
  45664. }
  45665. p3.subtractToRef(p2, this._edge);
  45666. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45667. edgeSquaredLength = this._edge.lengthSquared();
  45668. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45669. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45670. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45671. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45672. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45673. lowestRoot = getLowestRoot(a, b, c, t);
  45674. if (lowestRoot.found) {
  45675. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45676. if (f >= 0.0 && f <= 1.0) {
  45677. t = lowestRoot.root;
  45678. found = true;
  45679. this._edge.scaleInPlace(f);
  45680. p2.addToRef(this._edge, this._collisionPoint);
  45681. }
  45682. }
  45683. p1.subtractToRef(p3, this._edge);
  45684. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45685. edgeSquaredLength = this._edge.lengthSquared();
  45686. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45687. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45688. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45689. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45690. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45691. lowestRoot = getLowestRoot(a, b, c, t);
  45692. if (lowestRoot.found) {
  45693. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45694. if (f >= 0.0 && f <= 1.0) {
  45695. t = lowestRoot.root;
  45696. found = true;
  45697. this._edge.scaleInPlace(f);
  45698. p3.addToRef(this._edge, this._collisionPoint);
  45699. }
  45700. }
  45701. }
  45702. if (found) {
  45703. var distToCollision = t * this._velocity.length();
  45704. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45705. if (!this.intersectionPoint) {
  45706. this.intersectionPoint = this._collisionPoint.clone();
  45707. }
  45708. else {
  45709. this.intersectionPoint.copyFrom(this._collisionPoint);
  45710. }
  45711. this._nearestDistance = distToCollision;
  45712. this.collisionFound = true;
  45713. }
  45714. }
  45715. };
  45716. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45717. for (var i = indexStart; i < indexEnd; i += 3) {
  45718. var p1 = pts[indices[i] - decal];
  45719. var p2 = pts[indices[i + 1] - decal];
  45720. var p3 = pts[indices[i + 2] - decal];
  45721. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45722. }
  45723. };
  45724. Collider.prototype._getResponse = function (pos, vel) {
  45725. pos.addToRef(vel, this._destinationPoint);
  45726. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45727. this._basePoint.addToRef(vel, pos);
  45728. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45729. this._slidePlaneNormal.normalize();
  45730. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45731. pos.addInPlace(this._displacementVector);
  45732. this.intersectionPoint.addInPlace(this._displacementVector);
  45733. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45734. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45735. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45736. };
  45737. return Collider;
  45738. }());
  45739. BABYLON.Collider = Collider;
  45740. })(BABYLON || (BABYLON = {}));
  45741. //# sourceMappingURL=babylon.collider.js.map
  45742. var BABYLON;
  45743. (function (BABYLON) {
  45744. //WebWorker code will be inserted to this variable.
  45745. BABYLON.CollisionWorker = "";
  45746. var WorkerTaskType;
  45747. (function (WorkerTaskType) {
  45748. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45749. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45750. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45751. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45752. var WorkerReplyType;
  45753. (function (WorkerReplyType) {
  45754. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45755. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45756. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45757. var CollisionCoordinatorWorker = /** @class */ (function () {
  45758. function CollisionCoordinatorWorker() {
  45759. var _this = this;
  45760. this._scaledPosition = BABYLON.Vector3.Zero();
  45761. this._scaledVelocity = BABYLON.Vector3.Zero();
  45762. this.onMeshUpdated = function (transformNode) {
  45763. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45764. };
  45765. this.onGeometryUpdated = function (geometry) {
  45766. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45767. };
  45768. this._afterRender = function () {
  45769. if (!_this._init)
  45770. return;
  45771. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45772. return;
  45773. }
  45774. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45775. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45776. if (_this._runningUpdated > 4) {
  45777. return;
  45778. }
  45779. ++_this._runningUpdated;
  45780. var payload = {
  45781. updatedMeshes: _this._addUpdateMeshesList,
  45782. updatedGeometries: _this._addUpdateGeometriesList,
  45783. removedGeometries: _this._toRemoveGeometryArray,
  45784. removedMeshes: _this._toRemoveMeshesArray
  45785. };
  45786. var message = {
  45787. payload: payload,
  45788. taskType: WorkerTaskType.UPDATE
  45789. };
  45790. var serializable = [];
  45791. for (var id in payload.updatedGeometries) {
  45792. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45793. //prepare transferables
  45794. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45795. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45796. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45797. }
  45798. }
  45799. _this._worker.postMessage(message, serializable);
  45800. _this._addUpdateMeshesList = {};
  45801. _this._addUpdateGeometriesList = {};
  45802. _this._toRemoveGeometryArray = [];
  45803. _this._toRemoveMeshesArray = [];
  45804. };
  45805. this._onMessageFromWorker = function (e) {
  45806. var returnData = e.data;
  45807. if (returnData.error != WorkerReplyType.SUCCESS) {
  45808. //TODO what errors can be returned from the worker?
  45809. BABYLON.Tools.Warn("error returned from worker!");
  45810. return;
  45811. }
  45812. switch (returnData.taskType) {
  45813. case WorkerTaskType.INIT:
  45814. _this._init = true;
  45815. //Update the worked with ALL of the scene's current state
  45816. _this._scene.meshes.forEach(function (mesh) {
  45817. _this.onMeshAdded(mesh);
  45818. });
  45819. _this._scene.getGeometries().forEach(function (geometry) {
  45820. _this.onGeometryAdded(geometry);
  45821. });
  45822. break;
  45823. case WorkerTaskType.UPDATE:
  45824. _this._runningUpdated--;
  45825. break;
  45826. case WorkerTaskType.COLLIDE:
  45827. var returnPayload = returnData.payload;
  45828. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45829. return;
  45830. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45831. if (callback) {
  45832. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45833. if (mesh) {
  45834. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45835. }
  45836. }
  45837. //cleanup
  45838. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45839. break;
  45840. }
  45841. };
  45842. this._collisionsCallbackArray = [];
  45843. this._init = false;
  45844. this._runningUpdated = 0;
  45845. this._addUpdateMeshesList = {};
  45846. this._addUpdateGeometriesList = {};
  45847. this._toRemoveGeometryArray = [];
  45848. this._toRemoveMeshesArray = [];
  45849. }
  45850. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45851. if (!this._init)
  45852. return;
  45853. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45854. return;
  45855. position.divideToRef(collider._radius, this._scaledPosition);
  45856. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45857. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45858. var payload = {
  45859. collider: {
  45860. position: this._scaledPosition.asArray(),
  45861. velocity: this._scaledVelocity.asArray(),
  45862. radius: collider._radius.asArray()
  45863. },
  45864. collisionId: collisionIndex,
  45865. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45866. maximumRetry: maximumRetry
  45867. };
  45868. var message = {
  45869. payload: payload,
  45870. taskType: WorkerTaskType.COLLIDE
  45871. };
  45872. this._worker.postMessage(message);
  45873. };
  45874. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45875. this._scene = scene;
  45876. this._scene.registerAfterRender(this._afterRender);
  45877. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45878. this._worker = new Worker(workerUrl);
  45879. this._worker.onmessage = this._onMessageFromWorker;
  45880. var message = {
  45881. payload: {},
  45882. taskType: WorkerTaskType.INIT
  45883. };
  45884. this._worker.postMessage(message);
  45885. };
  45886. CollisionCoordinatorWorker.prototype.destroy = function () {
  45887. this._scene.unregisterAfterRender(this._afterRender);
  45888. this._worker.terminate();
  45889. };
  45890. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45891. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45892. this.onMeshUpdated(mesh);
  45893. };
  45894. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45895. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45896. };
  45897. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45898. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45899. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45900. this.onGeometryUpdated(geometry);
  45901. };
  45902. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45903. this._toRemoveGeometryArray.push(geometry.id);
  45904. };
  45905. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45906. var submeshes = [];
  45907. if (mesh.subMeshes) {
  45908. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45909. var boundingInfo = sm.getBoundingInfo();
  45910. return {
  45911. position: idx,
  45912. verticesStart: sm.verticesStart,
  45913. verticesCount: sm.verticesCount,
  45914. indexStart: sm.indexStart,
  45915. indexCount: sm.indexCount,
  45916. hasMaterial: !!sm.getMaterial(),
  45917. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45918. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45919. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45920. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45921. };
  45922. });
  45923. }
  45924. var geometryId = null;
  45925. if (mesh instanceof BABYLON.Mesh) {
  45926. var geometry = mesh.geometry;
  45927. geometryId = geometry ? geometry.id : null;
  45928. }
  45929. else if (mesh instanceof BABYLON.InstancedMesh) {
  45930. var geometry = mesh.sourceMesh.geometry;
  45931. geometryId = geometry ? geometry.id : null;
  45932. }
  45933. var boundingInfo = mesh.getBoundingInfo();
  45934. return {
  45935. uniqueId: mesh.uniqueId,
  45936. id: mesh.id,
  45937. name: mesh.name,
  45938. geometryId: geometryId,
  45939. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45940. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45941. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45942. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45943. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45944. subMeshes: submeshes,
  45945. checkCollisions: mesh.checkCollisions
  45946. };
  45947. };
  45948. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45949. return {
  45950. id: geometry.id,
  45951. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45952. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45953. indices: new Uint32Array(geometry.getIndices() || []),
  45954. };
  45955. };
  45956. return CollisionCoordinatorWorker;
  45957. }());
  45958. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45959. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45960. function CollisionCoordinatorLegacy() {
  45961. this._scaledPosition = BABYLON.Vector3.Zero();
  45962. this._scaledVelocity = BABYLON.Vector3.Zero();
  45963. this._finalPosition = BABYLON.Vector3.Zero();
  45964. }
  45965. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45966. position.divideToRef(collider._radius, this._scaledPosition);
  45967. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45968. collider.collidedMesh = null;
  45969. collider._retry = 0;
  45970. collider._initialVelocity = this._scaledVelocity;
  45971. collider._initialPosition = this._scaledPosition;
  45972. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45973. this._finalPosition.multiplyInPlace(collider._radius);
  45974. //run the callback
  45975. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45976. };
  45977. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45978. this._scene = scene;
  45979. };
  45980. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45981. //Legacy need no destruction method.
  45982. };
  45983. //No update in legacy mode
  45984. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45985. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45986. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45987. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45988. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45989. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45990. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45991. if (excludedMesh === void 0) { excludedMesh = null; }
  45992. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45993. if (collider._retry >= maximumRetry) {
  45994. finalPosition.copyFrom(position);
  45995. return;
  45996. }
  45997. // Check if this is a mesh else camera or -1
  45998. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  45999. collider._initialize(position, velocity, closeDistance);
  46000. // Check all meshes
  46001. for (var index = 0; index < this._scene.meshes.length; index++) {
  46002. var mesh = this._scene.meshes[index];
  46003. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46004. mesh._checkCollision(collider);
  46005. }
  46006. }
  46007. if (!collider.collisionFound) {
  46008. position.addToRef(velocity, finalPosition);
  46009. return;
  46010. }
  46011. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46012. collider._getResponse(position, velocity);
  46013. }
  46014. if (velocity.length() <= closeDistance) {
  46015. finalPosition.copyFrom(position);
  46016. return;
  46017. }
  46018. collider._retry++;
  46019. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46020. };
  46021. return CollisionCoordinatorLegacy;
  46022. }());
  46023. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46024. })(BABYLON || (BABYLON = {}));
  46025. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46026. var BABYLON;
  46027. (function (BABYLON) {
  46028. var Particle = /** @class */ (function () {
  46029. function Particle(particleSystem) {
  46030. this.particleSystem = particleSystem;
  46031. this.position = BABYLON.Vector3.Zero();
  46032. this.direction = BABYLON.Vector3.Zero();
  46033. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46034. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46035. this.lifeTime = 1.0;
  46036. this.age = 0;
  46037. this.size = 0;
  46038. this.angle = 0;
  46039. this.angularSpeed = 0;
  46040. this._currentFrameCounter = 0;
  46041. this.cellIndex = 0;
  46042. if (!this.particleSystem.isAnimationSheetEnabled) {
  46043. return;
  46044. }
  46045. this.cellIndex = this.particleSystem.startSpriteCellID;
  46046. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46047. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46048. }
  46049. else {
  46050. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46051. }
  46052. }
  46053. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46054. // (ageOffset / scaledUpdateSpeed) / available cells
  46055. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46056. this._currentFrameCounter += scaledUpdateSpeed;
  46057. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46058. this._currentFrameCounter = 0;
  46059. this.cellIndex++;
  46060. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46061. this.cellIndex = this.particleSystem.endSpriteCellID;
  46062. }
  46063. }
  46064. };
  46065. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46066. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46067. this.cellIndex++;
  46068. this._currentFrameCounter = 0;
  46069. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46070. if (this.particleSystem.spriteCellLoop) {
  46071. this.cellIndex = this.particleSystem.startSpriteCellID;
  46072. }
  46073. else {
  46074. this.cellIndex = this.particleSystem.endSpriteCellID;
  46075. }
  46076. }
  46077. }
  46078. else {
  46079. this._currentFrameCounter++;
  46080. }
  46081. };
  46082. Particle.prototype.copyTo = function (other) {
  46083. other.position.copyFrom(this.position);
  46084. other.direction.copyFrom(this.direction);
  46085. other.color.copyFrom(this.color);
  46086. other.colorStep.copyFrom(this.colorStep);
  46087. other.lifeTime = this.lifeTime;
  46088. other.age = this.age;
  46089. other.size = this.size;
  46090. other.angle = this.angle;
  46091. other.angularSpeed = this.angularSpeed;
  46092. other.particleSystem = this.particleSystem;
  46093. other.cellIndex = this.cellIndex;
  46094. };
  46095. return Particle;
  46096. }());
  46097. BABYLON.Particle = Particle;
  46098. })(BABYLON || (BABYLON = {}));
  46099. //# sourceMappingURL=babylon.particle.js.map
  46100. var BABYLON;
  46101. (function (BABYLON) {
  46102. var ParticleSystem = /** @class */ (function () {
  46103. // end of sheet animation
  46104. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46105. if (customEffect === void 0) { customEffect = null; }
  46106. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46107. if (epsilon === void 0) { epsilon = 0.01; }
  46108. var _this = this;
  46109. this.name = name;
  46110. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46111. // Members
  46112. this.animations = [];
  46113. this.renderingGroupId = 0;
  46114. this.emitter = null;
  46115. this.emitRate = 10;
  46116. this.manualEmitCount = -1;
  46117. this.updateSpeed = 0.01;
  46118. this.targetStopDuration = 0;
  46119. this.disposeOnStop = false;
  46120. this.minEmitPower = 1;
  46121. this.maxEmitPower = 1;
  46122. this.minLifeTime = 1;
  46123. this.maxLifeTime = 1;
  46124. this.minSize = 1;
  46125. this.maxSize = 1;
  46126. this.minAngularSpeed = 0;
  46127. this.maxAngularSpeed = 0;
  46128. this.layerMask = 0x0FFFFFFF;
  46129. this.customShader = null;
  46130. this.preventAutoStart = false;
  46131. /**
  46132. * An event triggered when the system is disposed.
  46133. * @type {BABYLON.Observable}
  46134. */
  46135. this.onDisposeObservable = new BABYLON.Observable();
  46136. this.onAnimationEnd = null;
  46137. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46138. this.forceDepthWrite = false;
  46139. this.gravity = BABYLON.Vector3.Zero();
  46140. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46141. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46142. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46143. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46144. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46145. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46146. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46147. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46148. this.particles = new Array();
  46149. this._stockParticles = new Array();
  46150. this._newPartsExcess = 0;
  46151. this._vertexBuffers = {};
  46152. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46153. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46154. this._scaledDirection = BABYLON.Vector3.Zero();
  46155. this._scaledGravity = BABYLON.Vector3.Zero();
  46156. this._currentRenderId = -1;
  46157. this._started = false;
  46158. this._stopped = false;
  46159. this._actualFrame = 0;
  46160. // sheet animation
  46161. this.startSpriteCellID = 0;
  46162. this.endSpriteCellID = 0;
  46163. this.spriteCellLoop = true;
  46164. this.spriteCellChangeSpeed = 0;
  46165. this.spriteCellWidth = 0;
  46166. this.spriteCellHeight = 0;
  46167. this._vertexBufferSize = 11;
  46168. this.appendParticleVertexes = null;
  46169. this.id = name;
  46170. this._capacity = capacity;
  46171. this._epsilon = epsilon;
  46172. if (_isAnimationSheetEnabled) {
  46173. this._vertexBufferSize = 12;
  46174. }
  46175. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46176. this._customEffect = customEffect;
  46177. scene.particleSystems.push(this);
  46178. this._createIndexBuffer();
  46179. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46180. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46181. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46182. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46183. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46184. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46185. if (this._isAnimationSheetEnabled) {
  46186. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46187. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46188. }
  46189. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46190. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46191. this._vertexBuffers["options"] = options;
  46192. // Default behaviors
  46193. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46194. this.updateFunction = function (particles) {
  46195. for (var index = 0; index < particles.length; index++) {
  46196. var particle = particles[index];
  46197. particle.age += _this._scaledUpdateSpeed;
  46198. if (particle.age >= particle.lifeTime) {
  46199. _this.recycleParticle(particle);
  46200. index--;
  46201. continue;
  46202. }
  46203. else {
  46204. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46205. particle.color.addInPlace(_this._scaledColorStep);
  46206. if (particle.color.a < 0)
  46207. particle.color.a = 0;
  46208. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46209. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46210. particle.position.addInPlace(_this._scaledDirection);
  46211. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46212. particle.direction.addInPlace(_this._scaledGravity);
  46213. if (_this._isAnimationSheetEnabled) {
  46214. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46215. }
  46216. }
  46217. }
  46218. };
  46219. }
  46220. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46221. set: function (callback) {
  46222. if (this._onDisposeObserver) {
  46223. this.onDisposeObservable.remove(this._onDisposeObserver);
  46224. }
  46225. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46226. },
  46227. enumerable: true,
  46228. configurable: true
  46229. });
  46230. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46231. get: function () {
  46232. return this._isAnimationSheetEnabled;
  46233. },
  46234. enumerable: true,
  46235. configurable: true
  46236. });
  46237. ParticleSystem.prototype._createIndexBuffer = function () {
  46238. var indices = [];
  46239. var index = 0;
  46240. for (var count = 0; count < this._capacity; count++) {
  46241. indices.push(index);
  46242. indices.push(index + 1);
  46243. indices.push(index + 2);
  46244. indices.push(index);
  46245. indices.push(index + 2);
  46246. indices.push(index + 3);
  46247. index += 4;
  46248. }
  46249. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46250. };
  46251. ParticleSystem.prototype.recycleParticle = function (particle) {
  46252. var lastParticle = this.particles.pop();
  46253. if (lastParticle !== particle) {
  46254. lastParticle.copyTo(particle);
  46255. this._stockParticles.push(lastParticle);
  46256. }
  46257. };
  46258. ParticleSystem.prototype.getCapacity = function () {
  46259. return this._capacity;
  46260. };
  46261. ParticleSystem.prototype.isAlive = function () {
  46262. return this._alive;
  46263. };
  46264. ParticleSystem.prototype.isStarted = function () {
  46265. return this._started;
  46266. };
  46267. ParticleSystem.prototype.start = function () {
  46268. this._started = true;
  46269. this._stopped = false;
  46270. this._actualFrame = 0;
  46271. };
  46272. ParticleSystem.prototype.stop = function () {
  46273. this._stopped = true;
  46274. };
  46275. // animation sheet
  46276. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46277. var offset = index * this._vertexBufferSize;
  46278. this._vertexData[offset] = particle.position.x;
  46279. this._vertexData[offset + 1] = particle.position.y;
  46280. this._vertexData[offset + 2] = particle.position.z;
  46281. this._vertexData[offset + 3] = particle.color.r;
  46282. this._vertexData[offset + 4] = particle.color.g;
  46283. this._vertexData[offset + 5] = particle.color.b;
  46284. this._vertexData[offset + 6] = particle.color.a;
  46285. this._vertexData[offset + 7] = particle.angle;
  46286. this._vertexData[offset + 8] = particle.size;
  46287. this._vertexData[offset + 9] = offsetX;
  46288. this._vertexData[offset + 10] = offsetY;
  46289. };
  46290. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46291. if (offsetX === 0)
  46292. offsetX = this._epsilon;
  46293. else if (offsetX === 1)
  46294. offsetX = 1 - this._epsilon;
  46295. if (offsetY === 0)
  46296. offsetY = this._epsilon;
  46297. else if (offsetY === 1)
  46298. offsetY = 1 - this._epsilon;
  46299. var offset = index * this._vertexBufferSize;
  46300. this._vertexData[offset] = particle.position.x;
  46301. this._vertexData[offset + 1] = particle.position.y;
  46302. this._vertexData[offset + 2] = particle.position.z;
  46303. this._vertexData[offset + 3] = particle.color.r;
  46304. this._vertexData[offset + 4] = particle.color.g;
  46305. this._vertexData[offset + 5] = particle.color.b;
  46306. this._vertexData[offset + 6] = particle.color.a;
  46307. this._vertexData[offset + 7] = particle.angle;
  46308. this._vertexData[offset + 8] = particle.size;
  46309. this._vertexData[offset + 9] = offsetX;
  46310. this._vertexData[offset + 10] = offsetY;
  46311. this._vertexData[offset + 11] = particle.cellIndex;
  46312. };
  46313. ParticleSystem.prototype._update = function (newParticles) {
  46314. // Update current
  46315. this._alive = this.particles.length > 0;
  46316. this.updateFunction(this.particles);
  46317. // Add new ones
  46318. var worldMatrix;
  46319. if (this.emitter.position) {
  46320. var emitterMesh = this.emitter;
  46321. worldMatrix = emitterMesh.getWorldMatrix();
  46322. }
  46323. else {
  46324. var emitterPosition = this.emitter;
  46325. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46326. }
  46327. var particle;
  46328. for (var index = 0; index < newParticles; index++) {
  46329. if (this.particles.length === this._capacity) {
  46330. break;
  46331. }
  46332. if (this._stockParticles.length !== 0) {
  46333. particle = this._stockParticles.pop();
  46334. particle.age = 0;
  46335. particle.cellIndex = this.startSpriteCellID;
  46336. }
  46337. else {
  46338. particle = new BABYLON.Particle(this);
  46339. }
  46340. this.particles.push(particle);
  46341. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46342. if (this.startDirectionFunction) {
  46343. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46344. }
  46345. else {
  46346. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46347. }
  46348. if (this.startPositionFunction) {
  46349. this.startPositionFunction(worldMatrix, particle.position, particle);
  46350. }
  46351. else {
  46352. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46353. }
  46354. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46355. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46356. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46357. var step = ParticleSystem.randomNumber(0, 1.0);
  46358. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46359. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46360. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46361. }
  46362. };
  46363. ParticleSystem.prototype._getEffect = function () {
  46364. if (this._customEffect) {
  46365. return this._customEffect;
  46366. }
  46367. ;
  46368. var defines = [];
  46369. if (this._scene.clipPlane) {
  46370. defines.push("#define CLIPPLANE");
  46371. }
  46372. if (this._isAnimationSheetEnabled) {
  46373. defines.push("#define ANIMATESHEET");
  46374. }
  46375. // Effect
  46376. var join = defines.join("\n");
  46377. if (this._cachedDefines !== join) {
  46378. this._cachedDefines = join;
  46379. var attributesNamesOrOptions;
  46380. var effectCreationOption;
  46381. if (this._isAnimationSheetEnabled) {
  46382. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46383. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46384. }
  46385. else {
  46386. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46387. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46388. }
  46389. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46390. }
  46391. return this._effect;
  46392. };
  46393. ParticleSystem.prototype.animate = function () {
  46394. if (!this._started)
  46395. return;
  46396. var effect = this._getEffect();
  46397. // Check
  46398. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46399. return;
  46400. if (this._currentRenderId === this._scene.getRenderId()) {
  46401. return;
  46402. }
  46403. this._currentRenderId = this._scene.getRenderId();
  46404. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46405. // determine the number of particles we need to create
  46406. var newParticles;
  46407. if (this.manualEmitCount > -1) {
  46408. newParticles = this.manualEmitCount;
  46409. this._newPartsExcess = 0;
  46410. this.manualEmitCount = 0;
  46411. }
  46412. else {
  46413. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46414. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46415. }
  46416. if (this._newPartsExcess > 1.0) {
  46417. newParticles += this._newPartsExcess >> 0;
  46418. this._newPartsExcess -= this._newPartsExcess >> 0;
  46419. }
  46420. this._alive = false;
  46421. if (!this._stopped) {
  46422. this._actualFrame += this._scaledUpdateSpeed;
  46423. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46424. this.stop();
  46425. }
  46426. else {
  46427. newParticles = 0;
  46428. }
  46429. this._update(newParticles);
  46430. // Stopped?
  46431. if (this._stopped) {
  46432. if (!this._alive) {
  46433. this._started = false;
  46434. if (this.onAnimationEnd) {
  46435. this.onAnimationEnd();
  46436. }
  46437. if (this.disposeOnStop) {
  46438. this._scene._toBeDisposed.push(this);
  46439. }
  46440. }
  46441. }
  46442. // Animation sheet
  46443. if (this._isAnimationSheetEnabled) {
  46444. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46445. }
  46446. else {
  46447. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46448. }
  46449. // Update VBO
  46450. var offset = 0;
  46451. for (var index = 0; index < this.particles.length; index++) {
  46452. var particle = this.particles[index];
  46453. this.appendParticleVertexes(offset, particle);
  46454. offset += 4;
  46455. }
  46456. if (this._vertexBuffer) {
  46457. this._vertexBuffer.update(this._vertexData);
  46458. }
  46459. };
  46460. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46461. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46462. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46463. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46464. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46465. };
  46466. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46467. this._appendParticleVertex(offset++, particle, 0, 0);
  46468. this._appendParticleVertex(offset++, particle, 1, 0);
  46469. this._appendParticleVertex(offset++, particle, 1, 1);
  46470. this._appendParticleVertex(offset++, particle, 0, 1);
  46471. };
  46472. ParticleSystem.prototype.rebuild = function () {
  46473. this._createIndexBuffer();
  46474. if (this._vertexBuffer) {
  46475. this._vertexBuffer._rebuild();
  46476. }
  46477. };
  46478. ParticleSystem.prototype.render = function () {
  46479. var effect = this._getEffect();
  46480. // Check
  46481. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46482. return 0;
  46483. var engine = this._scene.getEngine();
  46484. // Render
  46485. engine.enableEffect(effect);
  46486. engine.setState(false);
  46487. var viewMatrix = this._scene.getViewMatrix();
  46488. effect.setTexture("diffuseSampler", this.particleTexture);
  46489. effect.setMatrix("view", viewMatrix);
  46490. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46491. if (this._isAnimationSheetEnabled) {
  46492. var baseSize = this.particleTexture.getBaseSize();
  46493. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46494. }
  46495. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46496. if (this._scene.clipPlane) {
  46497. var clipPlane = this._scene.clipPlane;
  46498. var invView = viewMatrix.clone();
  46499. invView.invert();
  46500. effect.setMatrix("invView", invView);
  46501. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46502. }
  46503. // VBOs
  46504. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46505. // Draw order
  46506. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46507. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46508. }
  46509. else {
  46510. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46511. }
  46512. if (this.forceDepthWrite) {
  46513. engine.setDepthWrite(true);
  46514. }
  46515. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46516. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46517. return this.particles.length;
  46518. };
  46519. ParticleSystem.prototype.dispose = function () {
  46520. if (this._vertexBuffer) {
  46521. this._vertexBuffer.dispose();
  46522. this._vertexBuffer = null;
  46523. }
  46524. if (this._indexBuffer) {
  46525. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46526. this._indexBuffer = null;
  46527. }
  46528. if (this.particleTexture) {
  46529. this.particleTexture.dispose();
  46530. this.particleTexture = null;
  46531. }
  46532. // Remove from scene
  46533. var index = this._scene.particleSystems.indexOf(this);
  46534. if (index > -1) {
  46535. this._scene.particleSystems.splice(index, 1);
  46536. }
  46537. // Callback
  46538. this.onDisposeObservable.notifyObservers(this);
  46539. this.onDisposeObservable.clear();
  46540. };
  46541. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46542. if (radius === void 0) { radius = 1; }
  46543. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46544. this.particleEmitterType = particleEmitter;
  46545. return particleEmitter;
  46546. };
  46547. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46548. if (radius === void 0) { radius = 1; }
  46549. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46550. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46551. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46552. this.particleEmitterType = particleEmitter;
  46553. return particleEmitter;
  46554. };
  46555. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46556. if (radius === void 0) { radius = 1; }
  46557. if (angle === void 0) { angle = Math.PI / 4; }
  46558. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46559. this.particleEmitterType = particleEmitter;
  46560. return particleEmitter;
  46561. };
  46562. // 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.
  46563. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46564. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46565. this.direction1 = direction1;
  46566. this.direction2 = direction2;
  46567. this.minEmitBox = minEmitBox;
  46568. this.maxEmitBox = maxEmitBox;
  46569. this.particleEmitterType = particleEmitter;
  46570. return particleEmitter;
  46571. };
  46572. ParticleSystem.randomNumber = function (min, max) {
  46573. if (min === max) {
  46574. return (min);
  46575. }
  46576. var random = Math.random();
  46577. return ((random * (max - min)) + min);
  46578. };
  46579. // Clone
  46580. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46581. var custom = null;
  46582. var program = null;
  46583. if (this.customShader != null) {
  46584. program = this.customShader;
  46585. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46586. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46587. }
  46588. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46589. result.customShader = program;
  46590. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46591. if (newEmitter === undefined) {
  46592. newEmitter = this.emitter;
  46593. }
  46594. result.emitter = newEmitter;
  46595. if (this.particleTexture) {
  46596. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46597. }
  46598. if (!this.preventAutoStart) {
  46599. result.start();
  46600. }
  46601. return result;
  46602. };
  46603. ParticleSystem.prototype.serialize = function () {
  46604. var serializationObject = {};
  46605. serializationObject.name = this.name;
  46606. serializationObject.id = this.id;
  46607. // Emitter
  46608. if (this.emitter.position) {
  46609. var emitterMesh = this.emitter;
  46610. serializationObject.emitterId = emitterMesh.id;
  46611. }
  46612. else {
  46613. var emitterPosition = this.emitter;
  46614. serializationObject.emitter = emitterPosition.asArray();
  46615. }
  46616. serializationObject.capacity = this.getCapacity();
  46617. if (this.particleTexture) {
  46618. serializationObject.textureName = this.particleTexture.name;
  46619. }
  46620. // Animations
  46621. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46622. // Particle system
  46623. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46624. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46625. serializationObject.minSize = this.minSize;
  46626. serializationObject.maxSize = this.maxSize;
  46627. serializationObject.minEmitPower = this.minEmitPower;
  46628. serializationObject.maxEmitPower = this.maxEmitPower;
  46629. serializationObject.minLifeTime = this.minLifeTime;
  46630. serializationObject.maxLifeTime = this.maxLifeTime;
  46631. serializationObject.emitRate = this.emitRate;
  46632. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46633. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46634. serializationObject.gravity = this.gravity.asArray();
  46635. serializationObject.direction1 = this.direction1.asArray();
  46636. serializationObject.direction2 = this.direction2.asArray();
  46637. serializationObject.color1 = this.color1.asArray();
  46638. serializationObject.color2 = this.color2.asArray();
  46639. serializationObject.colorDead = this.colorDead.asArray();
  46640. serializationObject.updateSpeed = this.updateSpeed;
  46641. serializationObject.targetStopDuration = this.targetStopDuration;
  46642. serializationObject.textureMask = this.textureMask.asArray();
  46643. serializationObject.blendMode = this.blendMode;
  46644. serializationObject.customShader = this.customShader;
  46645. serializationObject.preventAutoStart = this.preventAutoStart;
  46646. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46647. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46648. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46649. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46650. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46651. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46652. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46653. return serializationObject;
  46654. };
  46655. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46656. var name = parsedParticleSystem.name;
  46657. var custom = null;
  46658. var program = null;
  46659. if (parsedParticleSystem.customShader) {
  46660. program = parsedParticleSystem.customShader;
  46661. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46662. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46663. }
  46664. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46665. particleSystem.customShader = program;
  46666. if (parsedParticleSystem.id) {
  46667. particleSystem.id = parsedParticleSystem.id;
  46668. }
  46669. // Auto start
  46670. if (parsedParticleSystem.preventAutoStart) {
  46671. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46672. }
  46673. // Texture
  46674. if (parsedParticleSystem.textureName) {
  46675. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46676. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46677. }
  46678. // Emitter
  46679. if (parsedParticleSystem.emitterId) {
  46680. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46681. }
  46682. else {
  46683. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46684. }
  46685. // Animations
  46686. if (parsedParticleSystem.animations) {
  46687. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46688. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46689. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46690. }
  46691. }
  46692. if (parsedParticleSystem.autoAnimate) {
  46693. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46694. }
  46695. // Particle system
  46696. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46697. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46698. particleSystem.minSize = parsedParticleSystem.minSize;
  46699. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46700. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46701. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46702. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46703. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46704. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46705. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46706. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46707. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46708. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46709. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46710. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46711. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46712. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46713. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46714. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46715. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46716. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46717. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46718. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46719. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46720. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46721. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46722. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46723. if (!particleSystem.preventAutoStart) {
  46724. particleSystem.start();
  46725. }
  46726. return particleSystem;
  46727. };
  46728. // Statics
  46729. ParticleSystem.BLENDMODE_ONEONE = 0;
  46730. ParticleSystem.BLENDMODE_STANDARD = 1;
  46731. return ParticleSystem;
  46732. }());
  46733. BABYLON.ParticleSystem = ParticleSystem;
  46734. })(BABYLON || (BABYLON = {}));
  46735. //# sourceMappingURL=babylon.particleSystem.js.map
  46736. var BABYLON;
  46737. (function (BABYLON) {
  46738. var BoxParticleEmitter = /** @class */ (function () {
  46739. // to be updated like the rest of emitters when breaking changes.
  46740. // all property should be come public variables and passed through constructor.
  46741. function BoxParticleEmitter(_particleSystem) {
  46742. this._particleSystem = _particleSystem;
  46743. }
  46744. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46745. get: function () {
  46746. return this._particleSystem.direction1;
  46747. },
  46748. set: function (value) {
  46749. this._particleSystem.direction1 = value;
  46750. },
  46751. enumerable: true,
  46752. configurable: true
  46753. });
  46754. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46755. get: function () {
  46756. return this._particleSystem.direction2;
  46757. },
  46758. set: function (value) {
  46759. this._particleSystem.direction2 = value;
  46760. },
  46761. enumerable: true,
  46762. configurable: true
  46763. });
  46764. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46765. get: function () {
  46766. return this._particleSystem.minEmitBox;
  46767. },
  46768. set: function (value) {
  46769. this._particleSystem.minEmitBox = value;
  46770. },
  46771. enumerable: true,
  46772. configurable: true
  46773. });
  46774. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46775. get: function () {
  46776. return this._particleSystem.maxEmitBox;
  46777. },
  46778. set: function (value) {
  46779. this._particleSystem.maxEmitBox = value;
  46780. },
  46781. enumerable: true,
  46782. configurable: true
  46783. });
  46784. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46785. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46786. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46787. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46788. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46789. };
  46790. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46791. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46792. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46793. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46794. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46795. };
  46796. return BoxParticleEmitter;
  46797. }());
  46798. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46799. })(BABYLON || (BABYLON = {}));
  46800. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46801. var BABYLON;
  46802. (function (BABYLON) {
  46803. var ConeParticleEmitter = /** @class */ (function () {
  46804. function ConeParticleEmitter(radius, angle) {
  46805. this.radius = radius;
  46806. this.angle = angle;
  46807. }
  46808. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46809. if (this.angle === 0) {
  46810. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46811. }
  46812. else {
  46813. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46814. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46815. var randX = Math.cos(phi) * Math.sin(theta);
  46816. var randY = Math.cos(theta);
  46817. var randZ = Math.sin(phi) * Math.sin(theta);
  46818. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46819. }
  46820. };
  46821. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46822. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46823. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46824. var randX = radius * Math.sin(s);
  46825. var randZ = radius * Math.cos(s);
  46826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46827. };
  46828. return ConeParticleEmitter;
  46829. }());
  46830. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46831. })(BABYLON || (BABYLON = {}));
  46832. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46833. var BABYLON;
  46834. (function (BABYLON) {
  46835. var SphereParticleEmitter = /** @class */ (function () {
  46836. function SphereParticleEmitter(radius) {
  46837. this.radius = radius;
  46838. }
  46839. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46840. // measure the direction Vector from the emitter to the particle.
  46841. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46842. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46843. };
  46844. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46845. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46846. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46847. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46848. var randY = this.radius * Math.cos(theta);
  46849. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46850. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46851. };
  46852. return SphereParticleEmitter;
  46853. }());
  46854. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46855. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46856. __extends(SphereDirectedParticleEmitter, _super);
  46857. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46858. var _this = _super.call(this, radius) || this;
  46859. _this.direction1 = direction1;
  46860. _this.direction2 = direction2;
  46861. return _this;
  46862. }
  46863. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46864. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46865. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46866. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46867. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46868. };
  46869. return SphereDirectedParticleEmitter;
  46870. }(SphereParticleEmitter));
  46871. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46872. })(BABYLON || (BABYLON = {}));
  46873. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46874. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46875. var BABYLON;
  46876. (function (BABYLON) {
  46877. var SolidParticle = /** @class */ (function () {
  46878. /**
  46879. * Creates a Solid Particle object.
  46880. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46881. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46882. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46883. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46884. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46885. * `shapeId` (integer) is the model shape identifier in the SPS.
  46886. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46887. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46888. */
  46889. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46890. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46891. this.idx = 0; // particle global index
  46892. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46893. this.position = BABYLON.Vector3.Zero(); // position
  46894. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46895. this.scaling = BABYLON.Vector3.One(); // scaling
  46896. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46897. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46898. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46899. this.alive = true; // alive
  46900. this.isVisible = true; // visibility
  46901. this._pos = 0; // index of this particle in the global "positions" array
  46902. this._ind = 0; // index of this particle in the global "indices" array
  46903. this.shapeId = 0; // model shape id
  46904. this.idxInShape = 0; // index of the particle in its shape id
  46905. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46906. this.idx = particleIndex;
  46907. this._pos = positionIndex;
  46908. this._ind = indiceIndex;
  46909. this._model = model;
  46910. this.shapeId = shapeId;
  46911. this.idxInShape = idxInShape;
  46912. this._sps = sps;
  46913. if (modelBoundingInfo) {
  46914. this._modelBoundingInfo = modelBoundingInfo;
  46915. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46916. }
  46917. }
  46918. Object.defineProperty(SolidParticle.prototype, "scale", {
  46919. /**
  46920. * legacy support, changed scale to scaling
  46921. */
  46922. get: function () {
  46923. return this.scaling;
  46924. },
  46925. set: function (scale) {
  46926. this.scaling = scale;
  46927. },
  46928. enumerable: true,
  46929. configurable: true
  46930. });
  46931. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46932. /**
  46933. * legacy support, changed quaternion to rotationQuaternion
  46934. */
  46935. get: function () {
  46936. return this.rotationQuaternion;
  46937. },
  46938. set: function (q) {
  46939. this.rotationQuaternion = q;
  46940. },
  46941. enumerable: true,
  46942. configurable: true
  46943. });
  46944. /**
  46945. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46946. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46947. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46948. */
  46949. SolidParticle.prototype.intersectsMesh = function (target) {
  46950. if (!this._boundingInfo || !target._boundingInfo) {
  46951. return false;
  46952. }
  46953. if (this._sps._bSphereOnly) {
  46954. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46955. }
  46956. return this._boundingInfo.intersects(target._boundingInfo, false);
  46957. };
  46958. return SolidParticle;
  46959. }());
  46960. BABYLON.SolidParticle = SolidParticle;
  46961. var ModelShape = /** @class */ (function () {
  46962. /**
  46963. * 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.
  46964. * SPS internal tool, don't use it manually.
  46965. */
  46966. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46967. this._indicesLength = 0; // length of the shape in the model indices array
  46968. this.shapeID = id;
  46969. this._shape = shape;
  46970. this._indicesLength = indicesLength;
  46971. this._shapeUV = shapeUV;
  46972. this._positionFunction = posFunction;
  46973. this._vertexFunction = vtxFunction;
  46974. }
  46975. return ModelShape;
  46976. }());
  46977. BABYLON.ModelShape = ModelShape;
  46978. var DepthSortedParticle = /** @class */ (function () {
  46979. function DepthSortedParticle() {
  46980. this.ind = 0; // index of the particle in the "indices" array
  46981. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46982. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46983. }
  46984. return DepthSortedParticle;
  46985. }());
  46986. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46987. })(BABYLON || (BABYLON = {}));
  46988. //# sourceMappingURL=babylon.solidParticle.js.map
  46989. var BABYLON;
  46990. (function (BABYLON) {
  46991. /**
  46992. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46993. */
  46994. var SolidParticleSystem = /** @class */ (function () {
  46995. /**
  46996. * Creates a SPS (Solid Particle System) object.
  46997. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46998. * `scene` (Scene) is the scene in which the SPS is added.
  46999. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47000. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47001. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47002. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47003. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47004. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47005. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47006. */
  47007. function SolidParticleSystem(name, scene, options) {
  47008. // public members
  47009. /**
  47010. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47011. * Example : var p = SPS.particles[i];
  47012. */
  47013. this.particles = new Array();
  47014. /**
  47015. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47016. */
  47017. this.nbParticles = 0;
  47018. /**
  47019. * If the particles must ever face the camera (default false). Useful for planar particles.
  47020. */
  47021. this.billboard = false;
  47022. /**
  47023. * Recompute normals when adding a shape
  47024. */
  47025. this.recomputeNormals = true;
  47026. /**
  47027. * This a counter ofr your own usage. It's not set by any SPS functions.
  47028. */
  47029. this.counter = 0;
  47030. /**
  47031. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47032. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47033. */
  47034. this.vars = {};
  47035. this._positions = new Array();
  47036. this._indices = new Array();
  47037. this._normals = new Array();
  47038. this._colors = new Array();
  47039. this._uvs = new Array();
  47040. this._index = 0; // indices index
  47041. this._updatable = true;
  47042. this._pickable = false;
  47043. this._isVisibilityBoxLocked = false;
  47044. this._alwaysVisible = false;
  47045. this._depthSort = false;
  47046. this._shapeCounter = 0;
  47047. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47048. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47049. this._computeParticleColor = true;
  47050. this._computeParticleTexture = true;
  47051. this._computeParticleRotation = true;
  47052. this._computeParticleVertex = false;
  47053. this._computeBoundingBox = false;
  47054. this._depthSortParticles = true;
  47055. this._cam_axisZ = BABYLON.Vector3.Zero();
  47056. this._cam_axisY = BABYLON.Vector3.Zero();
  47057. this._cam_axisX = BABYLON.Vector3.Zero();
  47058. this._axisZ = BABYLON.Axis.Z;
  47059. this._camDir = BABYLON.Vector3.Zero();
  47060. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47061. this._rotMatrix = new BABYLON.Matrix();
  47062. this._invertMatrix = new BABYLON.Matrix();
  47063. this._rotated = BABYLON.Vector3.Zero();
  47064. this._quaternion = new BABYLON.Quaternion();
  47065. this._vertex = BABYLON.Vector3.Zero();
  47066. this._normal = BABYLON.Vector3.Zero();
  47067. this._yaw = 0.0;
  47068. this._pitch = 0.0;
  47069. this._roll = 0.0;
  47070. this._halfroll = 0.0;
  47071. this._halfpitch = 0.0;
  47072. this._halfyaw = 0.0;
  47073. this._sinRoll = 0.0;
  47074. this._cosRoll = 0.0;
  47075. this._sinPitch = 0.0;
  47076. this._cosPitch = 0.0;
  47077. this._sinYaw = 0.0;
  47078. this._cosYaw = 0.0;
  47079. this._mustUnrotateFixedNormals = false;
  47080. this._minimum = BABYLON.Tmp.Vector3[0];
  47081. this._maximum = BABYLON.Tmp.Vector3[1];
  47082. this._minBbox = BABYLON.Tmp.Vector3[4];
  47083. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47084. this._particlesIntersect = false;
  47085. this._depthSortFunction = function (p1, p2) {
  47086. return (p2.sqDistance - p1.sqDistance);
  47087. };
  47088. this._needs32Bits = false;
  47089. this._bSphereOnly = false;
  47090. this._bSphereRadiusFactor = 1.0;
  47091. this.name = name;
  47092. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47093. this._camera = scene.activeCamera;
  47094. this._pickable = options ? options.isPickable : false;
  47095. this._depthSort = options ? options.enableDepthSort : false;
  47096. this._particlesIntersect = options ? options.particleIntersection : false;
  47097. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47098. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47099. if (options && options.updatable) {
  47100. this._updatable = options.updatable;
  47101. }
  47102. else {
  47103. this._updatable = true;
  47104. }
  47105. if (this._pickable) {
  47106. this.pickedParticles = [];
  47107. }
  47108. if (this._depthSort) {
  47109. this.depthSortedParticles = [];
  47110. }
  47111. }
  47112. /**
  47113. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47114. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47115. */
  47116. SolidParticleSystem.prototype.buildMesh = function () {
  47117. if (this.nbParticles === 0) {
  47118. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47119. this.addShape(triangle, 1);
  47120. triangle.dispose();
  47121. }
  47122. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47123. this._positions32 = new Float32Array(this._positions);
  47124. this._uvs32 = new Float32Array(this._uvs);
  47125. this._colors32 = new Float32Array(this._colors);
  47126. if (this.recomputeNormals) {
  47127. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47128. }
  47129. this._normals32 = new Float32Array(this._normals);
  47130. this._fixedNormal32 = new Float32Array(this._normals);
  47131. if (this._mustUnrotateFixedNormals) {
  47132. this._unrotateFixedNormals();
  47133. }
  47134. var vertexData = new BABYLON.VertexData();
  47135. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47136. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47137. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47138. if (this._uvs32) {
  47139. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47140. ;
  47141. }
  47142. if (this._colors32) {
  47143. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47144. }
  47145. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47146. vertexData.applyToMesh(mesh, this._updatable);
  47147. this.mesh = mesh;
  47148. this.mesh.isPickable = this._pickable;
  47149. // free memory
  47150. if (!this._depthSort) {
  47151. this._indices = null;
  47152. }
  47153. this._positions = null;
  47154. this._normals = null;
  47155. this._uvs = null;
  47156. this._colors = null;
  47157. if (!this._updatable) {
  47158. this.particles.length = 0;
  47159. }
  47160. return mesh;
  47161. };
  47162. /**
  47163. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47164. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47165. * Thus the particles generated from `digest()` have their property `position` set yet.
  47166. * `mesh` ( Mesh ) is the mesh to be digested
  47167. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47168. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47169. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47170. */
  47171. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47172. var size = (options && options.facetNb) || 1;
  47173. var number = (options && options.number) || 0;
  47174. var delta = (options && options.delta) || 0;
  47175. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47176. var meshInd = mesh.getIndices();
  47177. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47178. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47179. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47180. var f = 0; // facet counter
  47181. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47182. // compute size from number
  47183. if (number) {
  47184. number = (number > totalFacets) ? totalFacets : number;
  47185. size = Math.round(totalFacets / number);
  47186. delta = 0;
  47187. }
  47188. else {
  47189. size = (size > totalFacets) ? totalFacets : size;
  47190. }
  47191. var facetPos = []; // submesh positions
  47192. var facetInd = []; // submesh indices
  47193. var facetUV = []; // submesh UV
  47194. var facetCol = []; // submesh colors
  47195. var barycenter = BABYLON.Tmp.Vector3[0];
  47196. var sizeO = size;
  47197. while (f < totalFacets) {
  47198. size = sizeO + Math.floor((1 + delta) * Math.random());
  47199. if (f > totalFacets - size) {
  47200. size = totalFacets - f;
  47201. }
  47202. // reset temp arrays
  47203. facetPos.length = 0;
  47204. facetInd.length = 0;
  47205. facetUV.length = 0;
  47206. facetCol.length = 0;
  47207. // iterate over "size" facets
  47208. var fi = 0;
  47209. for (var j = f * 3; j < (f + size) * 3; j++) {
  47210. facetInd.push(fi);
  47211. var i = meshInd[j];
  47212. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47213. if (meshUV) {
  47214. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47215. }
  47216. if (meshCol) {
  47217. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47218. }
  47219. fi++;
  47220. }
  47221. // create a model shape for each single particle
  47222. var idx = this.nbParticles;
  47223. var shape = this._posToShape(facetPos);
  47224. var shapeUV = this._uvsToShapeUV(facetUV);
  47225. // compute the barycenter of the shape
  47226. var v;
  47227. for (v = 0; v < shape.length; v++) {
  47228. barycenter.addInPlace(shape[v]);
  47229. }
  47230. barycenter.scaleInPlace(1 / shape.length);
  47231. // shift the shape from its barycenter to the origin
  47232. for (v = 0; v < shape.length; v++) {
  47233. shape[v].subtractInPlace(barycenter);
  47234. }
  47235. var bInfo;
  47236. if (this._particlesIntersect) {
  47237. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47238. }
  47239. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47240. // add the particle in the SPS
  47241. var currentPos = this._positions.length;
  47242. var currentInd = this._indices.length;
  47243. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47244. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47245. // initialize the particle position
  47246. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47247. this._index += shape.length;
  47248. idx++;
  47249. this.nbParticles++;
  47250. this._shapeCounter++;
  47251. f += size;
  47252. }
  47253. return this;
  47254. };
  47255. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47256. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47257. var index = 0;
  47258. var idx = 0;
  47259. for (var p = 0; p < this.particles.length; p++) {
  47260. this._particle = this.particles[p];
  47261. this._shape = this._particle._model._shape;
  47262. if (this._particle.rotationQuaternion) {
  47263. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47264. }
  47265. else {
  47266. this._yaw = this._particle.rotation.y;
  47267. this._pitch = this._particle.rotation.x;
  47268. this._roll = this._particle.rotation.z;
  47269. this._quaternionRotationYPR();
  47270. }
  47271. this._quaternionToRotationMatrix();
  47272. this._rotMatrix.invertToRef(this._invertMatrix);
  47273. for (var pt = 0; pt < this._shape.length; pt++) {
  47274. idx = index + pt * 3;
  47275. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47276. this._fixedNormal32[idx] = this._normal.x;
  47277. this._fixedNormal32[idx + 1] = this._normal.y;
  47278. this._fixedNormal32[idx + 2] = this._normal.z;
  47279. }
  47280. index = idx + 3;
  47281. }
  47282. };
  47283. //reset copy
  47284. SolidParticleSystem.prototype._resetCopy = function () {
  47285. this._copy.position.x = 0;
  47286. this._copy.position.y = 0;
  47287. this._copy.position.z = 0;
  47288. this._copy.rotation.x = 0;
  47289. this._copy.rotation.y = 0;
  47290. this._copy.rotation.z = 0;
  47291. this._copy.rotationQuaternion = null;
  47292. this._copy.scaling.x = 1.0;
  47293. this._copy.scaling.y = 1.0;
  47294. this._copy.scaling.z = 1.0;
  47295. this._copy.uvs.x = 0;
  47296. this._copy.uvs.y = 0;
  47297. this._copy.uvs.z = 1.0;
  47298. this._copy.uvs.w = 1.0;
  47299. this._copy.color = null;
  47300. };
  47301. // _meshBuilder : inserts the shape model in the global SPS mesh
  47302. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47303. var i;
  47304. var u = 0;
  47305. var c = 0;
  47306. var n = 0;
  47307. this._resetCopy();
  47308. if (options && options.positionFunction) {
  47309. options.positionFunction(this._copy, idx, idxInShape);
  47310. this._mustUnrotateFixedNormals = true;
  47311. }
  47312. if (this._copy.rotationQuaternion) {
  47313. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47314. }
  47315. else {
  47316. this._yaw = this._copy.rotation.y;
  47317. this._pitch = this._copy.rotation.x;
  47318. this._roll = this._copy.rotation.z;
  47319. this._quaternionRotationYPR();
  47320. }
  47321. this._quaternionToRotationMatrix();
  47322. for (i = 0; i < shape.length; i++) {
  47323. this._vertex.x = shape[i].x;
  47324. this._vertex.y = shape[i].y;
  47325. this._vertex.z = shape[i].z;
  47326. if (options && options.vertexFunction) {
  47327. options.vertexFunction(this._copy, this._vertex, i);
  47328. }
  47329. this._vertex.x *= this._copy.scaling.x;
  47330. this._vertex.y *= this._copy.scaling.y;
  47331. this._vertex.z *= this._copy.scaling.z;
  47332. this._vertex.x += this._copy.pivot.x;
  47333. this._vertex.y += this._copy.pivot.y;
  47334. this._vertex.z += this._copy.pivot.z;
  47335. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47336. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47337. if (meshUV) {
  47338. 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);
  47339. u += 2;
  47340. }
  47341. if (this._copy.color) {
  47342. this._color = this._copy.color;
  47343. }
  47344. else if (meshCol && meshCol[c] !== undefined) {
  47345. this._color.r = meshCol[c];
  47346. this._color.g = meshCol[c + 1];
  47347. this._color.b = meshCol[c + 2];
  47348. this._color.a = meshCol[c + 3];
  47349. }
  47350. else {
  47351. this._color.r = 1.0;
  47352. this._color.g = 1.0;
  47353. this._color.b = 1.0;
  47354. this._color.a = 1.0;
  47355. }
  47356. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47357. c += 4;
  47358. if (!this.recomputeNormals && meshNor) {
  47359. this._normal.x = meshNor[n];
  47360. this._normal.y = meshNor[n + 1];
  47361. this._normal.z = meshNor[n + 2];
  47362. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47363. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47364. n += 3;
  47365. }
  47366. }
  47367. for (i = 0; i < meshInd.length; i++) {
  47368. var current_ind = p + meshInd[i];
  47369. indices.push(current_ind);
  47370. if (current_ind > 65535) {
  47371. this._needs32Bits = true;
  47372. }
  47373. }
  47374. if (this._pickable) {
  47375. var nbfaces = meshInd.length / 3;
  47376. for (i = 0; i < nbfaces; i++) {
  47377. this.pickedParticles.push({ idx: idx, faceId: i });
  47378. }
  47379. }
  47380. if (this._depthSort) {
  47381. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47382. }
  47383. return this._copy;
  47384. };
  47385. // returns a shape array from positions array
  47386. SolidParticleSystem.prototype._posToShape = function (positions) {
  47387. var shape = [];
  47388. for (var i = 0; i < positions.length; i += 3) {
  47389. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47390. }
  47391. return shape;
  47392. };
  47393. // returns a shapeUV array from a Vector4 uvs
  47394. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47395. var shapeUV = [];
  47396. if (uvs) {
  47397. for (var i = 0; i < uvs.length; i++)
  47398. shapeUV.push(uvs[i]);
  47399. }
  47400. return shapeUV;
  47401. };
  47402. // adds a new particle object in the particles array
  47403. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47404. if (bInfo === void 0) { bInfo = null; }
  47405. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47406. this.particles.push(sp);
  47407. return sp;
  47408. };
  47409. /**
  47410. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47411. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47412. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47413. * `nb` (positive integer) the number of particles to be created from this model
  47414. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47415. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47416. */
  47417. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47418. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47419. var meshInd = mesh.getIndices();
  47420. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47421. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47422. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47423. var bbInfo;
  47424. if (this._particlesIntersect) {
  47425. bbInfo = mesh.getBoundingInfo();
  47426. }
  47427. var shape = this._posToShape(meshPos);
  47428. var shapeUV = this._uvsToShapeUV(meshUV);
  47429. var posfunc = options ? options.positionFunction : null;
  47430. var vtxfunc = options ? options.vertexFunction : null;
  47431. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47432. // particles
  47433. var sp;
  47434. var currentCopy;
  47435. var idx = this.nbParticles;
  47436. for (var i = 0; i < nb; i++) {
  47437. var currentPos = this._positions.length;
  47438. var currentInd = this._indices.length;
  47439. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47440. if (this._updatable) {
  47441. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47442. sp.position.copyFrom(currentCopy.position);
  47443. sp.rotation.copyFrom(currentCopy.rotation);
  47444. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47445. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47446. }
  47447. if (currentCopy.color && sp.color) {
  47448. sp.color.copyFrom(currentCopy.color);
  47449. }
  47450. sp.scaling.copyFrom(currentCopy.scaling);
  47451. sp.uvs.copyFrom(currentCopy.uvs);
  47452. }
  47453. this._index += shape.length;
  47454. idx++;
  47455. }
  47456. this.nbParticles += nb;
  47457. this._shapeCounter++;
  47458. return this._shapeCounter - 1;
  47459. };
  47460. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47461. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47462. this._resetCopy();
  47463. if (particle._model._positionFunction) {
  47464. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47465. }
  47466. if (this._copy.rotationQuaternion) {
  47467. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47468. }
  47469. else {
  47470. this._yaw = this._copy.rotation.y;
  47471. this._pitch = this._copy.rotation.x;
  47472. this._roll = this._copy.rotation.z;
  47473. this._quaternionRotationYPR();
  47474. }
  47475. this._quaternionToRotationMatrix();
  47476. this._shape = particle._model._shape;
  47477. for (var pt = 0; pt < this._shape.length; pt++) {
  47478. this._vertex.x = this._shape[pt].x;
  47479. this._vertex.y = this._shape[pt].y;
  47480. this._vertex.z = this._shape[pt].z;
  47481. if (particle._model._vertexFunction) {
  47482. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47483. }
  47484. this._vertex.x *= this._copy.scaling.x;
  47485. this._vertex.y *= this._copy.scaling.y;
  47486. this._vertex.z *= this._copy.scaling.z;
  47487. this._vertex.x += this._copy.pivot.x;
  47488. this._vertex.y += this._copy.pivot.y;
  47489. this._vertex.z += this._copy.pivot.z;
  47490. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47491. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47492. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47493. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47494. }
  47495. particle.position.x = 0.0;
  47496. particle.position.y = 0.0;
  47497. particle.position.z = 0.0;
  47498. particle.rotation.x = 0.0;
  47499. particle.rotation.y = 0.0;
  47500. particle.rotation.z = 0.0;
  47501. particle.rotationQuaternion = null;
  47502. particle.scaling.x = 1.0;
  47503. particle.scaling.y = 1.0;
  47504. particle.scaling.z = 1.0;
  47505. };
  47506. /**
  47507. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47508. * Returns the SPS.
  47509. */
  47510. SolidParticleSystem.prototype.rebuildMesh = function () {
  47511. for (var p = 0; p < this.particles.length; p++) {
  47512. this._rebuildParticle(this.particles[p]);
  47513. }
  47514. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47515. return this;
  47516. };
  47517. /**
  47518. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47519. * This method calls `updateParticle()` for each particle of the SPS.
  47520. * For an animated SPS, it is usually called within the render loop.
  47521. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47522. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47523. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47524. * Returns the SPS.
  47525. */
  47526. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47527. if (start === void 0) { start = 0; }
  47528. if (end === void 0) { end = this.nbParticles - 1; }
  47529. if (update === void 0) { update = true; }
  47530. if (!this._updatable) {
  47531. return this;
  47532. }
  47533. // custom beforeUpdate
  47534. this.beforeUpdateParticles(start, end, update);
  47535. this._cam_axisX.x = 1.0;
  47536. this._cam_axisX.y = 0.0;
  47537. this._cam_axisX.z = 0.0;
  47538. this._cam_axisY.x = 0.0;
  47539. this._cam_axisY.y = 1.0;
  47540. this._cam_axisY.z = 0.0;
  47541. this._cam_axisZ.x = 0.0;
  47542. this._cam_axisZ.y = 0.0;
  47543. this._cam_axisZ.z = 1.0;
  47544. // cases when the World Matrix is to be computed first
  47545. if (this.billboard || this._depthSort) {
  47546. this.mesh.computeWorldMatrix(true);
  47547. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47548. }
  47549. // if the particles will always face the camera
  47550. if (this.billboard) {
  47551. // compute the camera position and un-rotate it by the current mesh rotation
  47552. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47553. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47554. this._cam_axisZ.normalize();
  47555. // same for camera up vector extracted from the cam view matrix
  47556. var view = this._camera.getViewMatrix(true);
  47557. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47558. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47559. this._cam_axisY.normalize();
  47560. this._cam_axisX.normalize();
  47561. }
  47562. // if depthSort, compute the camera global position in the mesh local system
  47563. if (this._depthSort) {
  47564. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47565. }
  47566. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47567. var idx = 0; // current position index in the global array positions32
  47568. var index = 0; // position start index in the global array positions32 of the current particle
  47569. var colidx = 0; // current color index in the global array colors32
  47570. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47571. var uvidx = 0; // current uv index in the global array uvs32
  47572. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47573. var pt = 0; // current index in the particle model shape
  47574. if (this.mesh.isFacetDataEnabled) {
  47575. this._computeBoundingBox = true;
  47576. }
  47577. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47578. if (this._computeBoundingBox) {
  47579. if (start == 0 && end == this.nbParticles - 1) {
  47580. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47581. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47582. }
  47583. else {
  47584. if (this.mesh._boundingInfo) {
  47585. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47586. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47587. }
  47588. }
  47589. }
  47590. // particle loop
  47591. index = this.particles[start]._pos;
  47592. var vpos = (index / 3) | 0;
  47593. colorIndex = vpos * 4;
  47594. uvIndex = vpos * 2;
  47595. for (var p = start; p <= end; p++) {
  47596. this._particle = this.particles[p];
  47597. this._shape = this._particle._model._shape;
  47598. this._shapeUV = this._particle._model._shapeUV;
  47599. // call to custom user function to update the particle properties
  47600. this.updateParticle(this._particle);
  47601. // camera-particle distance for depth sorting
  47602. if (this._depthSort && this._depthSortParticles) {
  47603. var dsp = this.depthSortedParticles[p];
  47604. dsp.ind = this._particle._ind;
  47605. dsp.indicesLength = this._particle._model._indicesLength;
  47606. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47607. }
  47608. // skip the computations for inactive or already invisible particles
  47609. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47610. // increment indexes for the next particle
  47611. pt = this._shape.length;
  47612. index += pt * 3;
  47613. colorIndex += pt * 4;
  47614. uvIndex += pt * 2;
  47615. continue;
  47616. }
  47617. if (this._particle.isVisible) {
  47618. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47619. // particle rotation matrix
  47620. if (this.billboard) {
  47621. this._particle.rotation.x = 0.0;
  47622. this._particle.rotation.y = 0.0;
  47623. }
  47624. if (this._computeParticleRotation || this.billboard) {
  47625. if (this._particle.rotationQuaternion) {
  47626. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47627. }
  47628. else {
  47629. this._yaw = this._particle.rotation.y;
  47630. this._pitch = this._particle.rotation.x;
  47631. this._roll = this._particle.rotation.z;
  47632. this._quaternionRotationYPR();
  47633. }
  47634. this._quaternionToRotationMatrix();
  47635. }
  47636. // particle vertex loop
  47637. for (pt = 0; pt < this._shape.length; pt++) {
  47638. idx = index + pt * 3;
  47639. colidx = colorIndex + pt * 4;
  47640. uvidx = uvIndex + pt * 2;
  47641. this._vertex.x = this._shape[pt].x;
  47642. this._vertex.y = this._shape[pt].y;
  47643. this._vertex.z = this._shape[pt].z;
  47644. if (this._computeParticleVertex) {
  47645. this.updateParticleVertex(this._particle, this._vertex, pt);
  47646. }
  47647. // positions
  47648. this._vertex.x *= this._particle.scaling.x;
  47649. this._vertex.y *= this._particle.scaling.y;
  47650. this._vertex.z *= this._particle.scaling.z;
  47651. this._vertex.x += this._particle.pivot.x;
  47652. this._vertex.y += this._particle.pivot.y;
  47653. this._vertex.z += this._particle.pivot.z;
  47654. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47655. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47656. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47657. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47658. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  47659. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  47660. if (this._computeBoundingBox) {
  47661. if (this._positions32[idx] < this._minimum.x) {
  47662. this._minimum.x = this._positions32[idx];
  47663. }
  47664. if (this._positions32[idx] > this._maximum.x) {
  47665. this._maximum.x = this._positions32[idx];
  47666. }
  47667. if (this._positions32[idx + 1] < this._minimum.y) {
  47668. this._minimum.y = this._positions32[idx + 1];
  47669. }
  47670. if (this._positions32[idx + 1] > this._maximum.y) {
  47671. this._maximum.y = this._positions32[idx + 1];
  47672. }
  47673. if (this._positions32[idx + 2] < this._minimum.z) {
  47674. this._minimum.z = this._positions32[idx + 2];
  47675. }
  47676. if (this._positions32[idx + 2] > this._maximum.z) {
  47677. this._maximum.z = this._positions32[idx + 2];
  47678. }
  47679. }
  47680. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47681. if (!this._computeParticleVertex) {
  47682. this._normal.x = this._fixedNormal32[idx];
  47683. this._normal.y = this._fixedNormal32[idx + 1];
  47684. this._normal.z = this._fixedNormal32[idx + 2];
  47685. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47686. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47687. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47688. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47689. 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;
  47690. 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;
  47691. }
  47692. if (this._computeParticleColor && this._particle.color) {
  47693. this._colors32[colidx] = this._particle.color.r;
  47694. this._colors32[colidx + 1] = this._particle.color.g;
  47695. this._colors32[colidx + 2] = this._particle.color.b;
  47696. this._colors32[colidx + 3] = this._particle.color.a;
  47697. }
  47698. if (this._computeParticleTexture) {
  47699. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47700. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47701. }
  47702. }
  47703. }
  47704. else {
  47705. this._particle._stillInvisible = true; // mark the particle as invisible
  47706. for (pt = 0; pt < this._shape.length; pt++) {
  47707. idx = index + pt * 3;
  47708. colidx = colorIndex + pt * 4;
  47709. uvidx = uvIndex + pt * 2;
  47710. this._positions32[idx] = 0.0;
  47711. this._positions32[idx + 1] = 0.0;
  47712. this._positions32[idx + 2] = 0.0;
  47713. this._normals32[idx] = 0.0;
  47714. this._normals32[idx + 1] = 0.0;
  47715. this._normals32[idx + 2] = 0.0;
  47716. if (this._computeParticleColor && this._particle.color) {
  47717. this._colors32[colidx] = this._particle.color.r;
  47718. this._colors32[colidx + 1] = this._particle.color.g;
  47719. this._colors32[colidx + 2] = this._particle.color.b;
  47720. this._colors32[colidx + 3] = this._particle.color.a;
  47721. }
  47722. if (this._computeParticleTexture) {
  47723. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47724. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47725. }
  47726. }
  47727. }
  47728. // if the particle intersections must be computed : update the bbInfo
  47729. if (this._particlesIntersect) {
  47730. var bInfo = this._particle._boundingInfo;
  47731. var bBox = bInfo.boundingBox;
  47732. var bSphere = bInfo.boundingSphere;
  47733. if (!this._bSphereOnly) {
  47734. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47735. for (var b = 0; b < bBox.vectors.length; b++) {
  47736. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47737. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47738. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47739. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47740. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47741. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47742. 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;
  47743. 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;
  47744. 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;
  47745. }
  47746. bBox._update(this.mesh._worldMatrix);
  47747. }
  47748. // place and scale the particle bouding sphere in the SPS local system, then update it
  47749. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47750. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47751. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47752. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47753. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47754. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47755. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47756. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47757. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47758. 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));
  47759. bSphere._update(this.mesh._worldMatrix);
  47760. }
  47761. // increment indexes for the next particle
  47762. index = idx + 3;
  47763. colorIndex = colidx + 4;
  47764. uvIndex = uvidx + 2;
  47765. }
  47766. // if the VBO must be updated
  47767. if (update) {
  47768. if (this._computeParticleColor) {
  47769. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47770. }
  47771. if (this._computeParticleTexture) {
  47772. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47773. }
  47774. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47775. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47776. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47777. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47778. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47779. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47780. for (var i = 0; i < this._normals32.length; i++) {
  47781. this._fixedNormal32[i] = this._normals32[i];
  47782. }
  47783. }
  47784. if (!this.mesh.areNormalsFrozen) {
  47785. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47786. }
  47787. }
  47788. if (this._depthSort && this._depthSortParticles) {
  47789. this.depthSortedParticles.sort(this._depthSortFunction);
  47790. var dspl = this.depthSortedParticles.length;
  47791. var sorted = 0;
  47792. var lind = 0;
  47793. var sind = 0;
  47794. var sid = 0;
  47795. for (sorted = 0; sorted < dspl; sorted++) {
  47796. lind = this.depthSortedParticles[sorted].indicesLength;
  47797. sind = this.depthSortedParticles[sorted].ind;
  47798. for (var i = 0; i < lind; i++) {
  47799. this._indices32[sid] = this._indices[sind + i];
  47800. sid++;
  47801. }
  47802. }
  47803. this.mesh.updateIndices(this._indices32);
  47804. }
  47805. }
  47806. if (this._computeBoundingBox) {
  47807. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47808. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47809. }
  47810. this.afterUpdateParticles(start, end, update);
  47811. return this;
  47812. };
  47813. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47814. this._halfroll = this._roll * 0.5;
  47815. this._halfpitch = this._pitch * 0.5;
  47816. this._halfyaw = this._yaw * 0.5;
  47817. this._sinRoll = Math.sin(this._halfroll);
  47818. this._cosRoll = Math.cos(this._halfroll);
  47819. this._sinPitch = Math.sin(this._halfpitch);
  47820. this._cosPitch = Math.cos(this._halfpitch);
  47821. this._sinYaw = Math.sin(this._halfyaw);
  47822. this._cosYaw = Math.cos(this._halfyaw);
  47823. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47824. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47825. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47826. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47827. };
  47828. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47829. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47830. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47831. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47832. this._rotMatrix.m[3] = 0;
  47833. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47834. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47835. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47836. this._rotMatrix.m[7] = 0;
  47837. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47838. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47839. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47840. this._rotMatrix.m[11] = 0;
  47841. this._rotMatrix.m[12] = 0;
  47842. this._rotMatrix.m[13] = 0;
  47843. this._rotMatrix.m[14] = 0;
  47844. this._rotMatrix.m[15] = 1.0;
  47845. };
  47846. /**
  47847. * Disposes the SPS.
  47848. * Returns nothing.
  47849. */
  47850. SolidParticleSystem.prototype.dispose = function () {
  47851. this.mesh.dispose();
  47852. this.vars = null;
  47853. // drop references to internal big arrays for the GC
  47854. this._positions = null;
  47855. this._indices = null;
  47856. this._normals = null;
  47857. this._uvs = null;
  47858. this._colors = null;
  47859. this._indices32 = null;
  47860. this._positions32 = null;
  47861. this._normals32 = null;
  47862. this._fixedNormal32 = null;
  47863. this._uvs32 = null;
  47864. this._colors32 = null;
  47865. this.pickedParticles = null;
  47866. };
  47867. /**
  47868. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47869. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47870. * Returns the SPS.
  47871. */
  47872. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47873. if (!this._isVisibilityBoxLocked) {
  47874. this.mesh.refreshBoundingInfo();
  47875. }
  47876. return this;
  47877. };
  47878. /**
  47879. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47880. * @param size the size (float) of the visibility box
  47881. * note : this doesn't lock the SPS mesh bounding box.
  47882. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47883. */
  47884. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47885. var vis = size / 2;
  47886. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47887. };
  47888. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47889. // getter and setter
  47890. get: function () {
  47891. return this._alwaysVisible;
  47892. },
  47893. /**
  47894. * Sets the SPS as always visible or not
  47895. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47896. */
  47897. set: function (val) {
  47898. this._alwaysVisible = val;
  47899. this.mesh.alwaysSelectAsActiveMesh = val;
  47900. },
  47901. enumerable: true,
  47902. configurable: true
  47903. });
  47904. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47905. get: function () {
  47906. return this._isVisibilityBoxLocked;
  47907. },
  47908. /**
  47909. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47910. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47911. */
  47912. set: function (val) {
  47913. this._isVisibilityBoxLocked = val;
  47914. var boundingInfo = this.mesh.getBoundingInfo();
  47915. boundingInfo.isLocked = val;
  47916. },
  47917. enumerable: true,
  47918. configurable: true
  47919. });
  47920. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47921. // getters
  47922. get: function () {
  47923. return this._computeParticleRotation;
  47924. },
  47925. // Optimizer setters
  47926. /**
  47927. * Tells to `setParticles()` to compute the particle rotations or not.
  47928. * Default value : true. The SPS is faster when it's set to false.
  47929. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47930. */
  47931. set: function (val) {
  47932. this._computeParticleRotation = val;
  47933. },
  47934. enumerable: true,
  47935. configurable: true
  47936. });
  47937. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47938. get: function () {
  47939. return this._computeParticleColor;
  47940. },
  47941. /**
  47942. * Tells to `setParticles()` to compute the particle colors or not.
  47943. * Default value : true. The SPS is faster when it's set to false.
  47944. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47945. */
  47946. set: function (val) {
  47947. this._computeParticleColor = val;
  47948. },
  47949. enumerable: true,
  47950. configurable: true
  47951. });
  47952. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47953. get: function () {
  47954. return this._computeParticleTexture;
  47955. },
  47956. /**
  47957. * Tells to `setParticles()` to compute the particle textures or not.
  47958. * Default value : true. The SPS is faster when it's set to false.
  47959. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47960. */
  47961. set: function (val) {
  47962. this._computeParticleTexture = val;
  47963. },
  47964. enumerable: true,
  47965. configurable: true
  47966. });
  47967. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47968. get: function () {
  47969. return this._computeParticleVertex;
  47970. },
  47971. /**
  47972. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47973. * Default value : false. The SPS is faster when it's set to false.
  47974. * Note : the particle custom vertex positions aren't stored values.
  47975. */
  47976. set: function (val) {
  47977. this._computeParticleVertex = val;
  47978. },
  47979. enumerable: true,
  47980. configurable: true
  47981. });
  47982. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47983. get: function () {
  47984. return this._computeBoundingBox;
  47985. },
  47986. /**
  47987. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47988. */
  47989. set: function (val) {
  47990. this._computeBoundingBox = val;
  47991. },
  47992. enumerable: true,
  47993. configurable: true
  47994. });
  47995. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  47996. get: function () {
  47997. return this._depthSortParticles;
  47998. },
  47999. /**
  48000. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48001. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48002. * Default : `true`
  48003. */
  48004. set: function (val) {
  48005. this._depthSortParticles = val;
  48006. },
  48007. enumerable: true,
  48008. configurable: true
  48009. });
  48010. // =======================================================================
  48011. // Particle behavior logic
  48012. // these following methods may be overwritten by the user to fit his needs
  48013. /**
  48014. * This function does nothing. It may be overwritten to set all the particle first values.
  48015. * The SPS doesn't call this function, you may have to call it by your own.
  48016. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48017. */
  48018. SolidParticleSystem.prototype.initParticles = function () {
  48019. };
  48020. /**
  48021. * This function does nothing. It may be overwritten to recycle a particle.
  48022. * The SPS doesn't call this function, you may have to call it by your own.
  48023. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48024. */
  48025. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48026. return particle;
  48027. };
  48028. /**
  48029. * Updates a particle : this function should be overwritten by the user.
  48030. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48031. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48032. * ex : just set a particle position or velocity and recycle conditions
  48033. */
  48034. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48035. return particle;
  48036. };
  48037. /**
  48038. * Updates a vertex of a particle : it can be overwritten by the user.
  48039. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48040. * @param particle the current particle
  48041. * @param vertex the current index of the current particle
  48042. * @param pt the index of the current vertex in the particle shape
  48043. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48044. * ex : just set a vertex particle position
  48045. */
  48046. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48047. return vertex;
  48048. };
  48049. /**
  48050. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48051. * This does nothing and may be overwritten by the user.
  48052. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48053. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48054. * @param update the boolean update value actually passed to setParticles()
  48055. */
  48056. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48057. };
  48058. /**
  48059. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48060. * This will be passed three parameters.
  48061. * This does nothing and may be overwritten by the user.
  48062. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48063. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48064. * @param update the boolean update value actually passed to setParticles()
  48065. */
  48066. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48067. };
  48068. return SolidParticleSystem;
  48069. }());
  48070. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48071. })(BABYLON || (BABYLON = {}));
  48072. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48073. var BABYLON;
  48074. (function (BABYLON) {
  48075. var ShaderMaterial = /** @class */ (function (_super) {
  48076. __extends(ShaderMaterial, _super);
  48077. function ShaderMaterial(name, scene, shaderPath, options) {
  48078. var _this = _super.call(this, name, scene) || this;
  48079. _this._textures = {};
  48080. _this._textureArrays = {};
  48081. _this._floats = {};
  48082. _this._ints = {};
  48083. _this._floatsArrays = {};
  48084. _this._colors3 = {};
  48085. _this._colors3Arrays = {};
  48086. _this._colors4 = {};
  48087. _this._vectors2 = {};
  48088. _this._vectors3 = {};
  48089. _this._vectors4 = {};
  48090. _this._matrices = {};
  48091. _this._matrices3x3 = {};
  48092. _this._matrices2x2 = {};
  48093. _this._vectors2Arrays = {};
  48094. _this._vectors3Arrays = {};
  48095. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48096. _this._shaderPath = shaderPath;
  48097. options.needAlphaBlending = options.needAlphaBlending || false;
  48098. options.needAlphaTesting = options.needAlphaTesting || false;
  48099. options.attributes = options.attributes || ["position", "normal", "uv"];
  48100. options.uniforms = options.uniforms || ["worldViewProjection"];
  48101. options.uniformBuffers = options.uniformBuffers || [];
  48102. options.samplers = options.samplers || [];
  48103. options.defines = options.defines || [];
  48104. _this._options = options;
  48105. return _this;
  48106. }
  48107. ShaderMaterial.prototype.getClassName = function () {
  48108. return "ShaderMaterial";
  48109. };
  48110. ShaderMaterial.prototype.needAlphaBlending = function () {
  48111. return this._options.needAlphaBlending;
  48112. };
  48113. ShaderMaterial.prototype.needAlphaTesting = function () {
  48114. return this._options.needAlphaTesting;
  48115. };
  48116. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48117. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48118. this._options.uniforms.push(uniformName);
  48119. }
  48120. };
  48121. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48122. if (this._options.samplers.indexOf(name) === -1) {
  48123. this._options.samplers.push(name);
  48124. }
  48125. this._textures[name] = texture;
  48126. return this;
  48127. };
  48128. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48129. if (this._options.samplers.indexOf(name) === -1) {
  48130. this._options.samplers.push(name);
  48131. }
  48132. this._checkUniform(name);
  48133. this._textureArrays[name] = textures;
  48134. return this;
  48135. };
  48136. ShaderMaterial.prototype.setFloat = function (name, value) {
  48137. this._checkUniform(name);
  48138. this._floats[name] = value;
  48139. return this;
  48140. };
  48141. ShaderMaterial.prototype.setInt = function (name, value) {
  48142. this._checkUniform(name);
  48143. this._ints[name] = value;
  48144. return this;
  48145. };
  48146. ShaderMaterial.prototype.setFloats = function (name, value) {
  48147. this._checkUniform(name);
  48148. this._floatsArrays[name] = value;
  48149. return this;
  48150. };
  48151. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48152. this._checkUniform(name);
  48153. this._colors3[name] = value;
  48154. return this;
  48155. };
  48156. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48157. this._checkUniform(name);
  48158. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48159. color.toArray(arr, arr.length);
  48160. return arr;
  48161. }, []);
  48162. return this;
  48163. };
  48164. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48165. this._checkUniform(name);
  48166. this._colors4[name] = value;
  48167. return this;
  48168. };
  48169. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48170. this._checkUniform(name);
  48171. this._vectors2[name] = value;
  48172. return this;
  48173. };
  48174. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48175. this._checkUniform(name);
  48176. this._vectors3[name] = value;
  48177. return this;
  48178. };
  48179. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48180. this._checkUniform(name);
  48181. this._vectors4[name] = value;
  48182. return this;
  48183. };
  48184. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48185. this._checkUniform(name);
  48186. this._matrices[name] = value;
  48187. return this;
  48188. };
  48189. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48190. this._checkUniform(name);
  48191. this._matrices3x3[name] = value;
  48192. return this;
  48193. };
  48194. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48195. this._checkUniform(name);
  48196. this._matrices2x2[name] = value;
  48197. return this;
  48198. };
  48199. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48200. this._checkUniform(name);
  48201. this._vectors2Arrays[name] = value;
  48202. return this;
  48203. };
  48204. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48205. this._checkUniform(name);
  48206. this._vectors3Arrays[name] = value;
  48207. return this;
  48208. };
  48209. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48210. if (!mesh) {
  48211. return true;
  48212. }
  48213. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48214. return false;
  48215. }
  48216. return false;
  48217. };
  48218. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48219. var scene = this.getScene();
  48220. var engine = scene.getEngine();
  48221. if (!this.checkReadyOnEveryCall) {
  48222. if (this._renderId === scene.getRenderId()) {
  48223. if (this._checkCache(scene, mesh, useInstances)) {
  48224. return true;
  48225. }
  48226. }
  48227. }
  48228. // Instances
  48229. var defines = [];
  48230. var attribs = [];
  48231. var fallbacks = new BABYLON.EffectFallbacks();
  48232. if (useInstances) {
  48233. defines.push("#define INSTANCES");
  48234. }
  48235. for (var index = 0; index < this._options.defines.length; index++) {
  48236. defines.push(this._options.defines[index]);
  48237. }
  48238. for (var index = 0; index < this._options.attributes.length; index++) {
  48239. attribs.push(this._options.attributes[index]);
  48240. }
  48241. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48242. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48243. defines.push("#define VERTEXCOLOR");
  48244. }
  48245. // Bones
  48246. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48249. if (mesh.numBoneInfluencers > 4) {
  48250. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48251. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48252. }
  48253. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48254. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48255. fallbacks.addCPUSkinningFallback(0, mesh);
  48256. if (this._options.uniforms.indexOf("mBones") === -1) {
  48257. this._options.uniforms.push("mBones");
  48258. }
  48259. }
  48260. else {
  48261. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48262. }
  48263. // Textures
  48264. for (var name in this._textures) {
  48265. if (!this._textures[name].isReady()) {
  48266. return false;
  48267. }
  48268. }
  48269. // Alpha test
  48270. if (engine.getAlphaTesting()) {
  48271. defines.push("#define ALPHATEST");
  48272. }
  48273. var previousEffect = this._effect;
  48274. var join = defines.join("\n");
  48275. this._effect = engine.createEffect(this._shaderPath, {
  48276. attributes: attribs,
  48277. uniformsNames: this._options.uniforms,
  48278. uniformBuffersNames: this._options.uniformBuffers,
  48279. samplers: this._options.samplers,
  48280. defines: join,
  48281. fallbacks: fallbacks,
  48282. onCompiled: this.onCompiled,
  48283. onError: this.onError
  48284. }, engine);
  48285. if (!this._effect.isReady()) {
  48286. return false;
  48287. }
  48288. if (previousEffect !== this._effect) {
  48289. scene.resetCachedMaterial();
  48290. }
  48291. this._renderId = scene.getRenderId();
  48292. return true;
  48293. };
  48294. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48295. var scene = this.getScene();
  48296. if (!this._effect) {
  48297. return;
  48298. }
  48299. if (this._options.uniforms.indexOf("world") !== -1) {
  48300. this._effect.setMatrix("world", world);
  48301. }
  48302. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48303. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48304. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48305. }
  48306. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48307. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48308. }
  48309. };
  48310. ShaderMaterial.prototype.bind = function (world, mesh) {
  48311. // Std values
  48312. this.bindOnlyWorldMatrix(world);
  48313. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48314. if (this._options.uniforms.indexOf("view") !== -1) {
  48315. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48316. }
  48317. if (this._options.uniforms.indexOf("projection") !== -1) {
  48318. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48319. }
  48320. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48321. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48322. }
  48323. // Bones
  48324. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48325. var name;
  48326. // Texture
  48327. for (name in this._textures) {
  48328. this._effect.setTexture(name, this._textures[name]);
  48329. }
  48330. // Texture arrays
  48331. for (name in this._textureArrays) {
  48332. this._effect.setTextureArray(name, this._textureArrays[name]);
  48333. }
  48334. // Int
  48335. for (name in this._ints) {
  48336. this._effect.setInt(name, this._ints[name]);
  48337. }
  48338. // Float
  48339. for (name in this._floats) {
  48340. this._effect.setFloat(name, this._floats[name]);
  48341. }
  48342. // Floats
  48343. for (name in this._floatsArrays) {
  48344. this._effect.setArray(name, this._floatsArrays[name]);
  48345. }
  48346. // Color3
  48347. for (name in this._colors3) {
  48348. this._effect.setColor3(name, this._colors3[name]);
  48349. }
  48350. for (name in this._colors3Arrays) {
  48351. this._effect.setArray3(name, this._colors3Arrays[name]);
  48352. }
  48353. // Color4
  48354. for (name in this._colors4) {
  48355. var color = this._colors4[name];
  48356. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48357. }
  48358. // Vector2
  48359. for (name in this._vectors2) {
  48360. this._effect.setVector2(name, this._vectors2[name]);
  48361. }
  48362. // Vector3
  48363. for (name in this._vectors3) {
  48364. this._effect.setVector3(name, this._vectors3[name]);
  48365. }
  48366. // Vector4
  48367. for (name in this._vectors4) {
  48368. this._effect.setVector4(name, this._vectors4[name]);
  48369. }
  48370. // Matrix
  48371. for (name in this._matrices) {
  48372. this._effect.setMatrix(name, this._matrices[name]);
  48373. }
  48374. // Matrix 3x3
  48375. for (name in this._matrices3x3) {
  48376. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48377. }
  48378. // Matrix 2x2
  48379. for (name in this._matrices2x2) {
  48380. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48381. }
  48382. // Vector2Array
  48383. for (name in this._vectors2Arrays) {
  48384. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48385. }
  48386. // Vector3Array
  48387. for (name in this._vectors3Arrays) {
  48388. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48389. }
  48390. }
  48391. this._afterBind(mesh);
  48392. };
  48393. ShaderMaterial.prototype.getActiveTextures = function () {
  48394. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48395. for (var name in this._textures) {
  48396. activeTextures.push(this._textures[name]);
  48397. }
  48398. for (var name in this._textureArrays) {
  48399. var array = this._textureArrays[name];
  48400. for (var index = 0; index < array.length; index++) {
  48401. activeTextures.push(array[index]);
  48402. }
  48403. }
  48404. return activeTextures;
  48405. };
  48406. ShaderMaterial.prototype.hasTexture = function (texture) {
  48407. if (_super.prototype.hasTexture.call(this, texture)) {
  48408. return true;
  48409. }
  48410. for (var name in this._textures) {
  48411. if (this._textures[name] === texture) {
  48412. return true;
  48413. }
  48414. }
  48415. for (var name in this._textureArrays) {
  48416. var array = this._textureArrays[name];
  48417. for (var index = 0; index < array.length; index++) {
  48418. if (array[index] === texture) {
  48419. return true;
  48420. }
  48421. }
  48422. }
  48423. return false;
  48424. };
  48425. ShaderMaterial.prototype.clone = function (name) {
  48426. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48427. return newShaderMaterial;
  48428. };
  48429. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48430. if (forceDisposeTextures) {
  48431. var name;
  48432. for (name in this._textures) {
  48433. this._textures[name].dispose();
  48434. }
  48435. for (name in this._textureArrays) {
  48436. var array = this._textureArrays[name];
  48437. for (var index = 0; index < array.length; index++) {
  48438. array[index].dispose();
  48439. }
  48440. }
  48441. }
  48442. this._textures = {};
  48443. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48444. };
  48445. ShaderMaterial.prototype.serialize = function () {
  48446. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48447. serializationObject.customType = "BABYLON.ShaderMaterial";
  48448. serializationObject.options = this._options;
  48449. serializationObject.shaderPath = this._shaderPath;
  48450. var name;
  48451. // Texture
  48452. serializationObject.textures = {};
  48453. for (name in this._textures) {
  48454. serializationObject.textures[name] = this._textures[name].serialize();
  48455. }
  48456. // Texture arrays
  48457. serializationObject.textureArrays = {};
  48458. for (name in this._textureArrays) {
  48459. serializationObject.textureArrays[name] = [];
  48460. var array = this._textureArrays[name];
  48461. for (var index = 0; index < array.length; index++) {
  48462. serializationObject.textureArrays[name].push(array[index].serialize());
  48463. }
  48464. }
  48465. // Float
  48466. serializationObject.floats = {};
  48467. for (name in this._floats) {
  48468. serializationObject.floats[name] = this._floats[name];
  48469. }
  48470. // Float s
  48471. serializationObject.FloatArrays = {};
  48472. for (name in this._floatsArrays) {
  48473. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48474. }
  48475. // Color3
  48476. serializationObject.colors3 = {};
  48477. for (name in this._colors3) {
  48478. serializationObject.colors3[name] = this._colors3[name].asArray();
  48479. }
  48480. // Color3 array
  48481. serializationObject.colors3Arrays = {};
  48482. for (name in this._colors3Arrays) {
  48483. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48484. }
  48485. // Color4
  48486. serializationObject.colors4 = {};
  48487. for (name in this._colors4) {
  48488. serializationObject.colors4[name] = this._colors4[name].asArray();
  48489. }
  48490. // Vector2
  48491. serializationObject.vectors2 = {};
  48492. for (name in this._vectors2) {
  48493. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48494. }
  48495. // Vector3
  48496. serializationObject.vectors3 = {};
  48497. for (name in this._vectors3) {
  48498. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48499. }
  48500. // Vector4
  48501. serializationObject.vectors4 = {};
  48502. for (name in this._vectors4) {
  48503. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48504. }
  48505. // Matrix
  48506. serializationObject.matrices = {};
  48507. for (name in this._matrices) {
  48508. serializationObject.matrices[name] = this._matrices[name].asArray();
  48509. }
  48510. // Matrix 3x3
  48511. serializationObject.matrices3x3 = {};
  48512. for (name in this._matrices3x3) {
  48513. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48514. }
  48515. // Matrix 2x2
  48516. serializationObject.matrices2x2 = {};
  48517. for (name in this._matrices2x2) {
  48518. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48519. }
  48520. // Vector2Array
  48521. serializationObject.vectors2Arrays = {};
  48522. for (name in this._vectors2Arrays) {
  48523. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48524. }
  48525. // Vector3Array
  48526. serializationObject.vectors3Arrays = {};
  48527. for (name in this._vectors3Arrays) {
  48528. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48529. }
  48530. return serializationObject;
  48531. };
  48532. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48533. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48534. var name;
  48535. // Texture
  48536. for (name in source.textures) {
  48537. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48538. }
  48539. // Texture arrays
  48540. for (name in source.textureArrays) {
  48541. var array = source.textureArrays[name];
  48542. var textureArray = new Array();
  48543. for (var index = 0; index < array.length; index++) {
  48544. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48545. }
  48546. material.setTextureArray(name, textureArray);
  48547. }
  48548. // Float
  48549. for (name in source.floats) {
  48550. material.setFloat(name, source.floats[name]);
  48551. }
  48552. // Float s
  48553. for (name in source.floatsArrays) {
  48554. material.setFloats(name, source.floatsArrays[name]);
  48555. }
  48556. // Color3
  48557. for (name in source.colors3) {
  48558. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48559. }
  48560. // Color3 arrays
  48561. for (name in source.colors3Arrays) {
  48562. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48563. if (i % 3 === 0) {
  48564. arr.push([num]);
  48565. }
  48566. else {
  48567. arr[arr.length - 1].push(num);
  48568. }
  48569. return arr;
  48570. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48571. material.setColor3Array(name, colors);
  48572. }
  48573. // Color4
  48574. for (name in source.colors4) {
  48575. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48576. }
  48577. // Vector2
  48578. for (name in source.vectors2) {
  48579. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48580. }
  48581. // Vector3
  48582. for (name in source.vectors3) {
  48583. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48584. }
  48585. // Vector4
  48586. for (name in source.vectors4) {
  48587. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48588. }
  48589. // Matrix
  48590. for (name in source.matrices) {
  48591. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48592. }
  48593. // Matrix 3x3
  48594. for (name in source.matrices3x3) {
  48595. material.setMatrix3x3(name, source.matrices3x3[name]);
  48596. }
  48597. // Matrix 2x2
  48598. for (name in source.matrices2x2) {
  48599. material.setMatrix2x2(name, source.matrices2x2[name]);
  48600. }
  48601. // Vector2Array
  48602. for (name in source.vectors2Arrays) {
  48603. material.setArray2(name, source.vectors2Arrays[name]);
  48604. }
  48605. // Vector3Array
  48606. for (name in source.vectors3Arrays) {
  48607. material.setArray3(name, source.vectors3Arrays[name]);
  48608. }
  48609. return material;
  48610. };
  48611. return ShaderMaterial;
  48612. }(BABYLON.Material));
  48613. BABYLON.ShaderMaterial = ShaderMaterial;
  48614. })(BABYLON || (BABYLON = {}));
  48615. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48616. var BABYLON;
  48617. (function (BABYLON) {
  48618. var GroundMesh = /** @class */ (function (_super) {
  48619. __extends(GroundMesh, _super);
  48620. function GroundMesh(name, scene) {
  48621. var _this = _super.call(this, name, scene) || this;
  48622. _this.generateOctree = false;
  48623. return _this;
  48624. }
  48625. GroundMesh.prototype.getClassName = function () {
  48626. return "GroundMesh";
  48627. };
  48628. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48629. get: function () {
  48630. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48631. },
  48632. enumerable: true,
  48633. configurable: true
  48634. });
  48635. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48636. get: function () {
  48637. return this._subdivisionsX;
  48638. },
  48639. enumerable: true,
  48640. configurable: true
  48641. });
  48642. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48643. get: function () {
  48644. return this._subdivisionsY;
  48645. },
  48646. enumerable: true,
  48647. configurable: true
  48648. });
  48649. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48650. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48651. this._subdivisionsX = chunksCount;
  48652. this._subdivisionsY = chunksCount;
  48653. this.subdivide(chunksCount);
  48654. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48655. };
  48656. /**
  48657. * Returns a height (y) value in the Worl system :
  48658. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48659. * Returns the ground y position if (x, z) are outside the ground surface.
  48660. */
  48661. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48662. var world = this.getWorldMatrix();
  48663. var invMat = BABYLON.Tmp.Matrix[5];
  48664. world.invertToRef(invMat);
  48665. var tmpVect = BABYLON.Tmp.Vector3[8];
  48666. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48667. x = tmpVect.x;
  48668. z = tmpVect.z;
  48669. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48670. return this.position.y;
  48671. }
  48672. if (!this._heightQuads || this._heightQuads.length == 0) {
  48673. this._initHeightQuads();
  48674. this._computeHeightQuads();
  48675. }
  48676. var facet = this._getFacetAt(x, z);
  48677. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48678. // return y in the World system
  48679. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48680. return tmpVect.y;
  48681. };
  48682. /**
  48683. * Returns a normalized vector (Vector3) orthogonal to the ground
  48684. * at the ground coordinates (x, z) expressed in the World system.
  48685. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48686. */
  48687. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48688. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48689. this.getNormalAtCoordinatesToRef(x, z, normal);
  48690. return normal;
  48691. };
  48692. /**
  48693. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48694. * at the ground coordinates (x, z) expressed in the World system.
  48695. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48696. * Returns the GroundMesh.
  48697. */
  48698. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48699. var world = this.getWorldMatrix();
  48700. var tmpMat = BABYLON.Tmp.Matrix[5];
  48701. world.invertToRef(tmpMat);
  48702. var tmpVect = BABYLON.Tmp.Vector3[8];
  48703. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48704. x = tmpVect.x;
  48705. z = tmpVect.z;
  48706. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48707. return this;
  48708. }
  48709. if (!this._heightQuads || this._heightQuads.length == 0) {
  48710. this._initHeightQuads();
  48711. this._computeHeightQuads();
  48712. }
  48713. var facet = this._getFacetAt(x, z);
  48714. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48715. return this;
  48716. };
  48717. /**
  48718. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48719. * if the ground has been updated.
  48720. * This can be used in the render loop.
  48721. * Returns the GroundMesh.
  48722. */
  48723. GroundMesh.prototype.updateCoordinateHeights = function () {
  48724. if (!this._heightQuads || this._heightQuads.length == 0) {
  48725. this._initHeightQuads();
  48726. }
  48727. this._computeHeightQuads();
  48728. return this;
  48729. };
  48730. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48731. GroundMesh.prototype._getFacetAt = function (x, z) {
  48732. // retrieve col and row from x, z coordinates in the ground local system
  48733. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48734. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48735. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48736. var facet;
  48737. if (z < quad.slope.x * x + quad.slope.y) {
  48738. facet = quad.facet1;
  48739. }
  48740. else {
  48741. facet = quad.facet2;
  48742. }
  48743. return facet;
  48744. };
  48745. // Creates and populates the heightMap array with "facet" elements :
  48746. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48747. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48748. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48749. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48750. // Returns the GroundMesh.
  48751. GroundMesh.prototype._initHeightQuads = function () {
  48752. var subdivisionsX = this._subdivisionsX;
  48753. var subdivisionsY = this._subdivisionsY;
  48754. this._heightQuads = new Array();
  48755. for (var row = 0; row < subdivisionsY; row++) {
  48756. for (var col = 0; col < subdivisionsX; col++) {
  48757. 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) };
  48758. this._heightQuads[row * subdivisionsX + col] = quad;
  48759. }
  48760. }
  48761. return this;
  48762. };
  48763. // Compute each quad element values and update the the heightMap array :
  48764. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48765. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48766. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48767. // Returns the GroundMesh.
  48768. GroundMesh.prototype._computeHeightQuads = function () {
  48769. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48770. if (!positions) {
  48771. return this;
  48772. }
  48773. var v1 = BABYLON.Tmp.Vector3[3];
  48774. var v2 = BABYLON.Tmp.Vector3[2];
  48775. var v3 = BABYLON.Tmp.Vector3[1];
  48776. var v4 = BABYLON.Tmp.Vector3[0];
  48777. var v1v2 = BABYLON.Tmp.Vector3[4];
  48778. var v1v3 = BABYLON.Tmp.Vector3[5];
  48779. var v1v4 = BABYLON.Tmp.Vector3[6];
  48780. var norm1 = BABYLON.Tmp.Vector3[7];
  48781. var norm2 = BABYLON.Tmp.Vector3[8];
  48782. var i = 0;
  48783. var j = 0;
  48784. var k = 0;
  48785. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48786. var h = 0;
  48787. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48788. var d2 = 0;
  48789. var subdivisionsX = this._subdivisionsX;
  48790. var subdivisionsY = this._subdivisionsY;
  48791. for (var row = 0; row < subdivisionsY; row++) {
  48792. for (var col = 0; col < subdivisionsX; col++) {
  48793. i = col * 3;
  48794. j = row * (subdivisionsX + 1) * 3;
  48795. k = (row + 1) * (subdivisionsX + 1) * 3;
  48796. v1.x = positions[j + i];
  48797. v1.y = positions[j + i + 1];
  48798. v1.z = positions[j + i + 2];
  48799. v2.x = positions[j + i + 3];
  48800. v2.y = positions[j + i + 4];
  48801. v2.z = positions[j + i + 5];
  48802. v3.x = positions[k + i];
  48803. v3.y = positions[k + i + 1];
  48804. v3.z = positions[k + i + 2];
  48805. v4.x = positions[k + i + 3];
  48806. v4.y = positions[k + i + 4];
  48807. v4.z = positions[k + i + 5];
  48808. // 2D slope V1V4
  48809. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48810. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48811. // facet equations :
  48812. // we compute each facet normal vector
  48813. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48814. // we compute the value d by applying the equation to v1 which belongs to the plane
  48815. // then we store the facet equation in a Vector4
  48816. v2.subtractToRef(v1, v1v2);
  48817. v3.subtractToRef(v1, v1v3);
  48818. v4.subtractToRef(v1, v1v4);
  48819. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48820. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48821. norm1.normalize();
  48822. norm2.normalize();
  48823. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48824. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48825. var quad = this._heightQuads[row * subdivisionsX + col];
  48826. quad.slope.copyFromFloats(cd, h);
  48827. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48828. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48829. }
  48830. }
  48831. return this;
  48832. };
  48833. GroundMesh.prototype.serialize = function (serializationObject) {
  48834. _super.prototype.serialize.call(this, serializationObject);
  48835. serializationObject.subdivisionsX = this._subdivisionsX;
  48836. serializationObject.subdivisionsY = this._subdivisionsY;
  48837. serializationObject.minX = this._minX;
  48838. serializationObject.maxX = this._maxX;
  48839. serializationObject.minZ = this._minZ;
  48840. serializationObject.maxZ = this._maxZ;
  48841. serializationObject.width = this._width;
  48842. serializationObject.height = this._height;
  48843. };
  48844. GroundMesh.Parse = function (parsedMesh, scene) {
  48845. var result = new GroundMesh(parsedMesh.name, scene);
  48846. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48847. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48848. result._minX = parsedMesh.minX;
  48849. result._maxX = parsedMesh.maxX;
  48850. result._minZ = parsedMesh.minZ;
  48851. result._maxZ = parsedMesh.maxZ;
  48852. result._width = parsedMesh.width;
  48853. result._height = parsedMesh.height;
  48854. return result;
  48855. };
  48856. return GroundMesh;
  48857. }(BABYLON.Mesh));
  48858. BABYLON.GroundMesh = GroundMesh;
  48859. })(BABYLON || (BABYLON = {}));
  48860. //# sourceMappingURL=babylon.groundMesh.js.map
  48861. var BABYLON;
  48862. (function (BABYLON) {
  48863. /**
  48864. * Creates an instance based on a source mesh.
  48865. */
  48866. var InstancedMesh = /** @class */ (function (_super) {
  48867. __extends(InstancedMesh, _super);
  48868. function InstancedMesh(name, source) {
  48869. var _this = _super.call(this, name, source.getScene()) || this;
  48870. source.instances.push(_this);
  48871. _this._sourceMesh = source;
  48872. _this.position.copyFrom(source.position);
  48873. _this.rotation.copyFrom(source.rotation);
  48874. _this.scaling.copyFrom(source.scaling);
  48875. if (source.rotationQuaternion) {
  48876. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48877. }
  48878. _this.infiniteDistance = source.infiniteDistance;
  48879. _this.setPivotMatrix(source.getPivotMatrix());
  48880. _this.refreshBoundingInfo();
  48881. _this._syncSubMeshes();
  48882. return _this;
  48883. }
  48884. /**
  48885. * Returns the string "InstancedMesh".
  48886. */
  48887. InstancedMesh.prototype.getClassName = function () {
  48888. return "InstancedMesh";
  48889. };
  48890. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48891. // Methods
  48892. get: function () {
  48893. return this._sourceMesh.receiveShadows;
  48894. },
  48895. enumerable: true,
  48896. configurable: true
  48897. });
  48898. Object.defineProperty(InstancedMesh.prototype, "material", {
  48899. get: function () {
  48900. return this._sourceMesh.material;
  48901. },
  48902. enumerable: true,
  48903. configurable: true
  48904. });
  48905. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48906. get: function () {
  48907. return this._sourceMesh.visibility;
  48908. },
  48909. enumerable: true,
  48910. configurable: true
  48911. });
  48912. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48913. get: function () {
  48914. return this._sourceMesh.skeleton;
  48915. },
  48916. enumerable: true,
  48917. configurable: true
  48918. });
  48919. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48920. get: function () {
  48921. return this._sourceMesh.renderingGroupId;
  48922. },
  48923. enumerable: true,
  48924. configurable: true
  48925. });
  48926. /**
  48927. * Returns the total number of vertices (integer).
  48928. */
  48929. InstancedMesh.prototype.getTotalVertices = function () {
  48930. return this._sourceMesh.getTotalVertices();
  48931. };
  48932. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48933. get: function () {
  48934. return this._sourceMesh;
  48935. },
  48936. enumerable: true,
  48937. configurable: true
  48938. });
  48939. /**
  48940. * Is this node ready to be used/rendered
  48941. * @return {boolean} is it ready
  48942. */
  48943. InstancedMesh.prototype.isReady = function () {
  48944. return this._sourceMesh.isReady(true);
  48945. };
  48946. /**
  48947. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48948. */
  48949. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48950. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48951. };
  48952. /**
  48953. * Sets the vertex data of the mesh geometry for the requested `kind`.
  48954. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  48955. * The `data` are either a numeric array either a Float32Array.
  48956. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  48957. * 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).
  48958. * Note that a new underlying VertexBuffer object is created each call.
  48959. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  48960. *
  48961. * Possible `kind` values :
  48962. * - BABYLON.VertexBuffer.PositionKind
  48963. * - BABYLON.VertexBuffer.UVKind
  48964. * - BABYLON.VertexBuffer.UV2Kind
  48965. * - BABYLON.VertexBuffer.UV3Kind
  48966. * - BABYLON.VertexBuffer.UV4Kind
  48967. * - BABYLON.VertexBuffer.UV5Kind
  48968. * - BABYLON.VertexBuffer.UV6Kind
  48969. * - BABYLON.VertexBuffer.ColorKind
  48970. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48971. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48972. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48973. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48974. *
  48975. * Returns the Mesh.
  48976. */
  48977. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  48978. if (this.sourceMesh) {
  48979. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  48980. }
  48981. return this.sourceMesh;
  48982. };
  48983. /**
  48984. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  48985. * If the mesh has no geometry, it is simply returned as it is.
  48986. * The `data` are either a numeric array either a Float32Array.
  48987. * No new underlying VertexBuffer object is created.
  48988. * 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.
  48989. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  48990. *
  48991. * Possible `kind` values :
  48992. * - BABYLON.VertexBuffer.PositionKind
  48993. * - BABYLON.VertexBuffer.UVKind
  48994. * - BABYLON.VertexBuffer.UV2Kind
  48995. * - BABYLON.VertexBuffer.UV3Kind
  48996. * - BABYLON.VertexBuffer.UV4Kind
  48997. * - BABYLON.VertexBuffer.UV5Kind
  48998. * - BABYLON.VertexBuffer.UV6Kind
  48999. * - BABYLON.VertexBuffer.ColorKind
  49000. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49001. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49002. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49003. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49004. *
  49005. * Returns the Mesh.
  49006. */
  49007. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49008. if (this.sourceMesh) {
  49009. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49010. }
  49011. return this.sourceMesh;
  49012. };
  49013. /**
  49014. * Sets the mesh indices.
  49015. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49016. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49017. * This method creates a new index buffer each call.
  49018. * Returns the Mesh.
  49019. */
  49020. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49021. if (totalVertices === void 0) { totalVertices = null; }
  49022. if (this.sourceMesh) {
  49023. this.sourceMesh.setIndices(indices, totalVertices);
  49024. }
  49025. return this.sourceMesh;
  49026. };
  49027. /**
  49028. * Boolean : True if the mesh owns the requested kind of data.
  49029. */
  49030. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49031. return this._sourceMesh.isVerticesDataPresent(kind);
  49032. };
  49033. /**
  49034. * Returns an array of indices (IndicesArray).
  49035. */
  49036. InstancedMesh.prototype.getIndices = function () {
  49037. return this._sourceMesh.getIndices();
  49038. };
  49039. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49040. get: function () {
  49041. return this._sourceMesh._positions;
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. /**
  49047. * Sets a new updated BoundingInfo to the mesh.
  49048. * Returns the mesh.
  49049. */
  49050. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49051. var meshBB = this._sourceMesh.getBoundingInfo();
  49052. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49053. this._updateBoundingInfo();
  49054. return this;
  49055. };
  49056. InstancedMesh.prototype._preActivate = function () {
  49057. if (this._currentLOD) {
  49058. this._currentLOD._preActivate();
  49059. }
  49060. return this;
  49061. };
  49062. InstancedMesh.prototype._activate = function (renderId) {
  49063. if (this._currentLOD) {
  49064. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49065. }
  49066. return this;
  49067. };
  49068. /**
  49069. * Returns the current associated LOD AbstractMesh.
  49070. */
  49071. InstancedMesh.prototype.getLOD = function (camera) {
  49072. if (!camera) {
  49073. return this;
  49074. }
  49075. var boundingInfo = this.getBoundingInfo();
  49076. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49077. if (this._currentLOD === this.sourceMesh) {
  49078. return this;
  49079. }
  49080. return this._currentLOD;
  49081. };
  49082. InstancedMesh.prototype._syncSubMeshes = function () {
  49083. this.releaseSubMeshes();
  49084. if (this._sourceMesh.subMeshes) {
  49085. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49086. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49087. }
  49088. }
  49089. return this;
  49090. };
  49091. InstancedMesh.prototype._generatePointsArray = function () {
  49092. return this._sourceMesh._generatePointsArray();
  49093. };
  49094. /**
  49095. * Creates a new InstancedMesh from the current mesh.
  49096. * - name (string) : the cloned mesh name
  49097. * - newParent (optional Node) : the optional Node to parent the clone to.
  49098. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49099. *
  49100. * Returns the clone.
  49101. */
  49102. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49103. var result = this._sourceMesh.createInstance(name);
  49104. // Deep copy
  49105. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49106. // Bounding info
  49107. this.refreshBoundingInfo();
  49108. // Parent
  49109. if (newParent) {
  49110. result.parent = newParent;
  49111. }
  49112. if (!doNotCloneChildren) {
  49113. // Children
  49114. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49115. var mesh = this.getScene().meshes[index];
  49116. if (mesh.parent === this) {
  49117. mesh.clone(mesh.name, result);
  49118. }
  49119. }
  49120. }
  49121. result.computeWorldMatrix(true);
  49122. return result;
  49123. };
  49124. /**
  49125. * Disposes the InstancedMesh.
  49126. * Returns nothing.
  49127. */
  49128. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49129. // Remove from mesh
  49130. var index = this._sourceMesh.instances.indexOf(this);
  49131. this._sourceMesh.instances.splice(index, 1);
  49132. _super.prototype.dispose.call(this, doNotRecurse);
  49133. };
  49134. return InstancedMesh;
  49135. }(BABYLON.AbstractMesh));
  49136. BABYLON.InstancedMesh = InstancedMesh;
  49137. })(BABYLON || (BABYLON = {}));
  49138. //# sourceMappingURL=babylon.instancedMesh.js.map
  49139. var BABYLON;
  49140. (function (BABYLON) {
  49141. var LinesMesh = /** @class */ (function (_super) {
  49142. __extends(LinesMesh, _super);
  49143. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49144. if (scene === void 0) { scene = null; }
  49145. if (parent === void 0) { parent = null; }
  49146. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49147. _this.useVertexColor = useVertexColor;
  49148. _this.useVertexAlpha = useVertexAlpha;
  49149. _this.color = new BABYLON.Color3(1, 1, 1);
  49150. _this.alpha = 1;
  49151. if (source) {
  49152. _this.color = source.color.clone();
  49153. _this.alpha = source.alpha;
  49154. _this.useVertexColor = source.useVertexColor;
  49155. _this.useVertexAlpha = source.useVertexAlpha;
  49156. }
  49157. _this._intersectionThreshold = 0.1;
  49158. var defines = [];
  49159. var options = {
  49160. attributes: [BABYLON.VertexBuffer.PositionKind],
  49161. uniforms: ["world", "viewProjection"],
  49162. needAlphaBlending: true,
  49163. defines: defines
  49164. };
  49165. if (useVertexAlpha === false) {
  49166. options.needAlphaBlending = false;
  49167. }
  49168. if (!useVertexColor) {
  49169. options.uniforms.push("color");
  49170. }
  49171. else {
  49172. options.defines.push("#define VERTEXCOLOR");
  49173. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49174. }
  49175. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49176. return _this;
  49177. }
  49178. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49179. /**
  49180. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49181. * This margin is expressed in world space coordinates, so its value may vary.
  49182. * Default value is 0.1
  49183. * @returns the intersection Threshold value.
  49184. */
  49185. get: function () {
  49186. return this._intersectionThreshold;
  49187. },
  49188. /**
  49189. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49190. * This margin is expressed in world space coordinates, so its value may vary.
  49191. * @param value the new threshold to apply
  49192. */
  49193. set: function (value) {
  49194. if (this._intersectionThreshold === value) {
  49195. return;
  49196. }
  49197. this._intersectionThreshold = value;
  49198. if (this.geometry) {
  49199. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49200. }
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. /**
  49206. * Returns the string "LineMesh"
  49207. */
  49208. LinesMesh.prototype.getClassName = function () {
  49209. return "LinesMesh";
  49210. };
  49211. Object.defineProperty(LinesMesh.prototype, "material", {
  49212. get: function () {
  49213. return this._colorShader;
  49214. },
  49215. set: function (value) {
  49216. // Do nothing
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49222. get: function () {
  49223. return false;
  49224. },
  49225. enumerable: true,
  49226. configurable: true
  49227. });
  49228. LinesMesh.prototype.createInstance = function (name) {
  49229. throw new Error("LinesMeshes do not support createInstance.");
  49230. };
  49231. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49232. if (!this._geometry) {
  49233. return this;
  49234. }
  49235. // VBOs
  49236. this._geometry._bind(this._colorShader.getEffect());
  49237. // Color
  49238. if (!this.useVertexColor) {
  49239. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49240. }
  49241. return this;
  49242. };
  49243. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49244. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49245. return this;
  49246. }
  49247. var engine = this.getScene().getEngine();
  49248. // Draw order
  49249. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49250. return this;
  49251. };
  49252. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49253. this._colorShader.dispose();
  49254. _super.prototype.dispose.call(this, doNotRecurse);
  49255. };
  49256. /**
  49257. * Returns a new LineMesh object cloned from the current one.
  49258. */
  49259. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49260. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49261. };
  49262. return LinesMesh;
  49263. }(BABYLON.Mesh));
  49264. BABYLON.LinesMesh = LinesMesh;
  49265. })(BABYLON || (BABYLON = {}));
  49266. //# sourceMappingURL=babylon.linesMesh.js.map
  49267. var BABYLON;
  49268. (function (BABYLON) {
  49269. var MeshBuilder = /** @class */ (function () {
  49270. function MeshBuilder() {
  49271. }
  49272. MeshBuilder.updateSideOrientation = function (orientation) {
  49273. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49274. return BABYLON.Mesh.DOUBLESIDE;
  49275. }
  49276. if (orientation === undefined || orientation === null) {
  49277. return BABYLON.Mesh.FRONTSIDE;
  49278. }
  49279. return orientation;
  49280. };
  49281. /**
  49282. * Creates a box mesh.
  49283. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49284. * The parameter `size` sets the size (float) of each box side (default 1).
  49285. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49286. * 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).
  49287. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49289. * 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).
  49290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49292. */
  49293. MeshBuilder.CreateBox = function (name, options, scene) {
  49294. if (scene === void 0) { scene = null; }
  49295. var box = new BABYLON.Mesh(name, scene);
  49296. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49297. box._originalBuilderSideOrientation = options.sideOrientation;
  49298. var vertexData = BABYLON.VertexData.CreateBox(options);
  49299. vertexData.applyToMesh(box, options.updatable);
  49300. return box;
  49301. };
  49302. /**
  49303. * Creates a sphere mesh.
  49304. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49305. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49306. * 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`).
  49307. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49308. * 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
  49309. * 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).
  49310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49311. * 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).
  49312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49314. */
  49315. MeshBuilder.CreateSphere = function (name, options, scene) {
  49316. var sphere = new BABYLON.Mesh(name, scene);
  49317. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49318. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49319. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49320. vertexData.applyToMesh(sphere, options.updatable);
  49321. return sphere;
  49322. };
  49323. /**
  49324. * Creates a plane polygonal mesh. By default, this is a disc.
  49325. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49326. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49327. * 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.
  49328. * 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
  49329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49330. * 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).
  49331. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49333. */
  49334. MeshBuilder.CreateDisc = function (name, options, scene) {
  49335. if (scene === void 0) { scene = null; }
  49336. var disc = new BABYLON.Mesh(name, scene);
  49337. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49338. disc._originalBuilderSideOrientation = options.sideOrientation;
  49339. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49340. vertexData.applyToMesh(disc, options.updatable);
  49341. return disc;
  49342. };
  49343. /**
  49344. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49345. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49346. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49347. * 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`).
  49348. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49349. * 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.
  49350. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49351. * 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).
  49352. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49354. */
  49355. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49356. var sphere = new BABYLON.Mesh(name, scene);
  49357. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49358. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49359. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49360. vertexData.applyToMesh(sphere, options.updatable);
  49361. return sphere;
  49362. };
  49363. ;
  49364. /**
  49365. * Creates a ribbon mesh.
  49366. * 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.
  49367. *
  49368. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49369. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49370. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49371. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49372. * 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.
  49373. * 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.
  49374. * 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
  49375. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49376. * 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).
  49377. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49378. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49379. * 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.
  49380. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49381. * 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
  49382. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49383. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49385. */
  49386. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49387. if (scene === void 0) { scene = null; }
  49388. var pathArray = options.pathArray;
  49389. var closeArray = options.closeArray;
  49390. var closePath = options.closePath;
  49391. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49392. var instance = options.instance;
  49393. var updatable = options.updatable;
  49394. if (instance) {
  49395. // positionFunction : ribbon case
  49396. // only pathArray and sideOrientation parameters are taken into account for positions update
  49397. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49398. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49399. var positionFunction = function (positions) {
  49400. var minlg = pathArray[0].length;
  49401. var i = 0;
  49402. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49403. for (var si = 1; si <= ns; si++) {
  49404. for (var p = 0; p < pathArray.length; p++) {
  49405. var path = pathArray[p];
  49406. var l = path.length;
  49407. minlg = (minlg < l) ? minlg : l;
  49408. var j = 0;
  49409. while (j < minlg) {
  49410. positions[i] = path[j].x;
  49411. positions[i + 1] = path[j].y;
  49412. positions[i + 2] = path[j].z;
  49413. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49414. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49415. }
  49416. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49417. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49418. }
  49419. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49420. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49421. }
  49422. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49423. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49424. }
  49425. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49426. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49427. }
  49428. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49429. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49430. }
  49431. j++;
  49432. i += 3;
  49433. }
  49434. if (instance._closePath) {
  49435. positions[i] = path[0].x;
  49436. positions[i + 1] = path[0].y;
  49437. positions[i + 2] = path[0].z;
  49438. i += 3;
  49439. }
  49440. }
  49441. }
  49442. };
  49443. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49444. positionFunction(positions);
  49445. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49446. instance._boundingInfo.update(instance._worldMatrix);
  49447. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49448. if (options.colors) {
  49449. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49450. for (var c = 0; c < options.colors.length; c++) {
  49451. colors[c * 4] = options.colors[c].r;
  49452. colors[c * 4 + 1] = options.colors[c].g;
  49453. colors[c * 4 + 2] = options.colors[c].b;
  49454. colors[c * 4 + 3] = options.colors[c].a;
  49455. }
  49456. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49457. }
  49458. if (options.uvs) {
  49459. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49460. for (var i = 0; i < options.uvs.length; i++) {
  49461. uvs[i * 2] = options.uvs[i].x;
  49462. uvs[i * 2 + 1] = options.uvs[i].y;
  49463. }
  49464. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49465. }
  49466. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49467. var indices = instance.getIndices();
  49468. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49469. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49470. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49471. if (instance._closePath) {
  49472. var indexFirst = 0;
  49473. var indexLast = 0;
  49474. for (var p = 0; p < pathArray.length; p++) {
  49475. indexFirst = instance._idx[p] * 3;
  49476. if (p + 1 < pathArray.length) {
  49477. indexLast = (instance._idx[p + 1] - 1) * 3;
  49478. }
  49479. else {
  49480. indexLast = normals.length - 3;
  49481. }
  49482. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49483. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49484. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49485. normals[indexLast] = normals[indexFirst];
  49486. normals[indexLast + 1] = normals[indexFirst + 1];
  49487. normals[indexLast + 2] = normals[indexFirst + 2];
  49488. }
  49489. }
  49490. if (!(instance.areNormalsFrozen)) {
  49491. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49492. }
  49493. }
  49494. return instance;
  49495. }
  49496. else {
  49497. var ribbon = new BABYLON.Mesh(name, scene);
  49498. ribbon._originalBuilderSideOrientation = sideOrientation;
  49499. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49500. if (closePath) {
  49501. ribbon._idx = vertexData._idx;
  49502. }
  49503. ribbon._closePath = closePath;
  49504. ribbon._closeArray = closeArray;
  49505. vertexData.applyToMesh(ribbon, updatable);
  49506. return ribbon;
  49507. }
  49508. };
  49509. /**
  49510. * Creates a cylinder or a cone mesh.
  49511. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49512. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49513. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49514. * 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.
  49515. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49516. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49517. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49518. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49519. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49520. * 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).
  49521. * 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
  49522. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49523. * 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
  49524. * 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.
  49525. * If `enclose` is false, a ring surface is one element.
  49526. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49527. * 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
  49528. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49529. * 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).
  49530. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49532. */
  49533. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49534. var cylinder = new BABYLON.Mesh(name, scene);
  49535. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49536. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49537. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49538. vertexData.applyToMesh(cylinder, options.updatable);
  49539. return cylinder;
  49540. };
  49541. /**
  49542. * Creates a torus mesh.
  49543. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49544. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49545. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49546. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49548. * 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).
  49549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49551. */
  49552. MeshBuilder.CreateTorus = function (name, options, scene) {
  49553. var torus = new BABYLON.Mesh(name, scene);
  49554. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49555. torus._originalBuilderSideOrientation = options.sideOrientation;
  49556. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49557. vertexData.applyToMesh(torus, options.updatable);
  49558. return torus;
  49559. };
  49560. /**
  49561. * Creates a torus knot mesh.
  49562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49563. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49564. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49565. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49566. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49567. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49568. * 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).
  49569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49571. */
  49572. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49573. var torusKnot = new BABYLON.Mesh(name, scene);
  49574. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49575. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49576. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49577. vertexData.applyToMesh(torusKnot, options.updatable);
  49578. return torusKnot;
  49579. };
  49580. /**
  49581. * Creates a line system mesh.
  49582. * A line system is a pool of many lines gathered in a single mesh.
  49583. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49584. * 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.
  49585. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49586. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49587. * 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
  49588. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49589. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49590. * 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
  49591. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49593. */
  49594. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49595. var instance = options.instance;
  49596. var lines = options.lines;
  49597. var colors = options.colors;
  49598. if (instance) {
  49599. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49600. var vertexColor;
  49601. var lineColors;
  49602. if (colors) {
  49603. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49604. }
  49605. var i = 0;
  49606. var c = 0;
  49607. for (var l = 0; l < lines.length; l++) {
  49608. var points = lines[l];
  49609. for (var p = 0; p < points.length; p++) {
  49610. positions[i] = points[p].x;
  49611. positions[i + 1] = points[p].y;
  49612. positions[i + 2] = points[p].z;
  49613. if (colors && vertexColor) {
  49614. lineColors = colors[l];
  49615. vertexColor[c] = lineColors[p].r;
  49616. vertexColor[c + 1] = lineColors[p].g;
  49617. vertexColor[c + 2] = lineColors[p].b;
  49618. vertexColor[c + 3] = lineColors[p].a;
  49619. c += 4;
  49620. }
  49621. i += 3;
  49622. }
  49623. }
  49624. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49625. if (colors && vertexColor) {
  49626. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49627. }
  49628. return instance;
  49629. }
  49630. // line system creation
  49631. var useVertexColor = (colors) ? true : false;
  49632. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49633. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49634. vertexData.applyToMesh(lineSystem, options.updatable);
  49635. return lineSystem;
  49636. };
  49637. /**
  49638. * Creates a line mesh.
  49639. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49640. * 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.
  49641. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49642. * The parameter `points` is an array successive Vector3.
  49643. * 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
  49644. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49645. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49646. * When updating an instance, remember that only point positions can change, not the number of points.
  49647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49648. */
  49649. MeshBuilder.CreateLines = function (name, options, scene) {
  49650. if (scene === void 0) { scene = null; }
  49651. var colors = (options.colors) ? [options.colors] : null;
  49652. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49653. return lines;
  49654. };
  49655. /**
  49656. * Creates a dashed line mesh.
  49657. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49658. * 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.
  49659. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49660. * The parameter `points` is an array successive Vector3.
  49661. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49662. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49663. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49664. * 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
  49665. * When updating an instance, remember that only point positions can change, not the number of points.
  49666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49667. */
  49668. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49669. if (scene === void 0) { scene = null; }
  49670. var points = options.points;
  49671. var instance = options.instance;
  49672. var gapSize = options.gapSize || 1;
  49673. var dashSize = options.dashSize || 3;
  49674. if (instance) {
  49675. var positionFunction = function (positions) {
  49676. var curvect = BABYLON.Vector3.Zero();
  49677. var nbSeg = positions.length / 6;
  49678. var lg = 0;
  49679. var nb = 0;
  49680. var shft = 0;
  49681. var dashshft = 0;
  49682. var curshft = 0;
  49683. var p = 0;
  49684. var i = 0;
  49685. var j = 0;
  49686. for (i = 0; i < points.length - 1; i++) {
  49687. points[i + 1].subtractToRef(points[i], curvect);
  49688. lg += curvect.length();
  49689. }
  49690. shft = lg / nbSeg;
  49691. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49692. for (i = 0; i < points.length - 1; i++) {
  49693. points[i + 1].subtractToRef(points[i], curvect);
  49694. nb = Math.floor(curvect.length() / shft);
  49695. curvect.normalize();
  49696. j = 0;
  49697. while (j < nb && p < positions.length) {
  49698. curshft = shft * j;
  49699. positions[p] = points[i].x + curshft * curvect.x;
  49700. positions[p + 1] = points[i].y + curshft * curvect.y;
  49701. positions[p + 2] = points[i].z + curshft * curvect.z;
  49702. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49703. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49704. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49705. p += 6;
  49706. j++;
  49707. }
  49708. }
  49709. while (p < positions.length) {
  49710. positions[p] = points[i].x;
  49711. positions[p + 1] = points[i].y;
  49712. positions[p + 2] = points[i].z;
  49713. p += 3;
  49714. }
  49715. };
  49716. instance.updateMeshPositions(positionFunction, false);
  49717. return instance;
  49718. }
  49719. // dashed lines creation
  49720. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49721. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49722. vertexData.applyToMesh(dashedLines, options.updatable);
  49723. dashedLines.dashSize = dashSize;
  49724. dashedLines.gapSize = gapSize;
  49725. return dashedLines;
  49726. };
  49727. /**
  49728. * Creates an extruded shape mesh.
  49729. * 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.
  49730. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49731. *
  49732. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49733. * 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
  49734. * extruded along the Z axis.
  49735. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49736. * 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.
  49737. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49738. * 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
  49739. * 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
  49740. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49742. * 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).
  49743. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49744. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49746. */
  49747. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49748. if (scene === void 0) { scene = null; }
  49749. var path = options.path;
  49750. var shape = options.shape;
  49751. var scale = options.scale || 1;
  49752. var rotation = options.rotation || 0;
  49753. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49754. var updatable = options.updatable;
  49755. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49756. var instance = options.instance || null;
  49757. var invertUV = options.invertUV || false;
  49758. 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);
  49759. };
  49760. /**
  49761. * Creates an custom extruded shape mesh.
  49762. * 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.
  49763. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49764. *
  49765. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49766. * 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
  49767. * extruded along the Z axis.
  49768. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49769. * 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
  49770. * and the distance of this point from the begining of the path :
  49771. * ```javascript
  49772. * var rotationFunction = function(i, distance) {
  49773. * // do things
  49774. * return rotationValue; }
  49775. * ```
  49776. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49777. * 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
  49778. * and the distance of this point from the begining of the path :
  49779. * ```javascript
  49780. * var scaleFunction = function(i, distance) {
  49781. * // do things
  49782. * return scaleValue;}
  49783. * ```
  49784. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49785. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49786. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49787. * 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
  49788. * 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
  49789. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49790. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49791. * 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).
  49792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49793. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49795. */
  49796. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49797. var path = options.path;
  49798. var shape = options.shape;
  49799. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49800. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49801. var ribbonCloseArray = options.ribbonCloseArray || false;
  49802. var ribbonClosePath = options.ribbonClosePath || false;
  49803. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49804. var updatable = options.updatable;
  49805. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49806. var instance = options.instance;
  49807. var invertUV = options.invertUV || false;
  49808. 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);
  49809. };
  49810. /**
  49811. * Creates lathe mesh.
  49812. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49813. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49814. *
  49815. * 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
  49816. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49817. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49818. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49819. * 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.
  49820. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49821. * 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
  49822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49823. * 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).
  49824. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49825. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49827. */
  49828. MeshBuilder.CreateLathe = function (name, options, scene) {
  49829. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49830. var closed = (options.closed === undefined) ? true : options.closed;
  49831. var shape = options.shape;
  49832. var radius = options.radius || 1;
  49833. var tessellation = options.tessellation || 64;
  49834. var updatable = options.updatable;
  49835. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49836. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49837. var pi2 = Math.PI * 2;
  49838. var paths = new Array();
  49839. var invertUV = options.invertUV || false;
  49840. var i = 0;
  49841. var p = 0;
  49842. var step = pi2 / tessellation * arc;
  49843. var rotated;
  49844. var path = new Array();
  49845. ;
  49846. for (i = 0; i <= tessellation; i++) {
  49847. var path = [];
  49848. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49849. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49850. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49851. }
  49852. for (p = 0; p < shape.length; p++) {
  49853. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49854. path.push(rotated);
  49855. }
  49856. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49857. 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));
  49858. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49859. }
  49860. paths.push(path);
  49861. }
  49862. // lathe ribbon
  49863. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49864. return lathe;
  49865. };
  49866. /**
  49867. * Creates a plane mesh.
  49868. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49869. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49870. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49871. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49872. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49873. * 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).
  49874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49876. */
  49877. MeshBuilder.CreatePlane = function (name, options, scene) {
  49878. var plane = new BABYLON.Mesh(name, scene);
  49879. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49880. plane._originalBuilderSideOrientation = options.sideOrientation;
  49881. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49882. vertexData.applyToMesh(plane, options.updatable);
  49883. if (options.sourcePlane) {
  49884. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49885. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49886. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49887. plane.rotate(vectorProduct, product);
  49888. }
  49889. return plane;
  49890. };
  49891. /**
  49892. * Creates a ground mesh.
  49893. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49894. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49895. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49897. */
  49898. MeshBuilder.CreateGround = function (name, options, scene) {
  49899. var ground = new BABYLON.GroundMesh(name, scene);
  49900. ground._setReady(false);
  49901. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49902. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49903. ground._width = options.width || 1;
  49904. ground._height = options.height || 1;
  49905. ground._maxX = ground._width / 2;
  49906. ground._maxZ = ground._height / 2;
  49907. ground._minX = -ground._maxX;
  49908. ground._minZ = -ground._maxZ;
  49909. var vertexData = BABYLON.VertexData.CreateGround(options);
  49910. vertexData.applyToMesh(ground, options.updatable);
  49911. ground._setReady(true);
  49912. return ground;
  49913. };
  49914. /**
  49915. * Creates a tiled ground mesh.
  49916. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49917. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49918. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49919. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49920. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49921. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49922. * numbers of subdivisions on the ground width and height of each tile.
  49923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49924. */
  49925. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49926. var tiledGround = new BABYLON.Mesh(name, scene);
  49927. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49928. vertexData.applyToMesh(tiledGround, options.updatable);
  49929. return tiledGround;
  49930. };
  49931. /**
  49932. * Creates a ground mesh from a height map.
  49933. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49935. * The parameter `url` sets the URL of the height map image resource.
  49936. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49937. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49938. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49939. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49940. * 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.
  49941. * 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).
  49942. * This function is passed the newly built mesh :
  49943. * ```javascript
  49944. * function(mesh) { // do things
  49945. * return; }
  49946. * ```
  49947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49948. */
  49949. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49950. var width = options.width || 10.0;
  49951. var height = options.height || 10.0;
  49952. var subdivisions = options.subdivisions || 1 | 0;
  49953. var minHeight = options.minHeight || 0.0;
  49954. var maxHeight = options.maxHeight || 1.0;
  49955. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49956. var updatable = options.updatable;
  49957. var onReady = options.onReady;
  49958. var ground = new BABYLON.GroundMesh(name, scene);
  49959. ground._subdivisionsX = subdivisions;
  49960. ground._subdivisionsY = subdivisions;
  49961. ground._width = width;
  49962. ground._height = height;
  49963. ground._maxX = ground._width / 2.0;
  49964. ground._maxZ = ground._height / 2.0;
  49965. ground._minX = -ground._maxX;
  49966. ground._minZ = -ground._maxZ;
  49967. ground._setReady(false);
  49968. var onload = function (img) {
  49969. // Getting height map data
  49970. var canvas = document.createElement("canvas");
  49971. var context = canvas.getContext("2d");
  49972. if (!context) {
  49973. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49974. }
  49975. if (scene.isDisposed) {
  49976. return;
  49977. }
  49978. var bufferWidth = img.width;
  49979. var bufferHeight = img.height;
  49980. canvas.width = bufferWidth;
  49981. canvas.height = bufferHeight;
  49982. context.drawImage(img, 0, 0);
  49983. // Create VertexData from map data
  49984. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49985. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49986. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49987. width: width, height: height,
  49988. subdivisions: subdivisions,
  49989. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49990. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49991. });
  49992. vertexData.applyToMesh(ground, updatable);
  49993. ground._setReady(true);
  49994. //execute ready callback, if set
  49995. if (onReady) {
  49996. onReady(ground);
  49997. }
  49998. };
  49999. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50000. return ground;
  50001. };
  50002. /**
  50003. * Creates a polygon mesh.
  50004. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50005. * 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.
  50006. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50008. * 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).
  50009. * Remember you can only change the shape positions, not their number when updating a polygon.
  50010. */
  50011. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50012. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50013. var shape = options.shape;
  50014. var holes = options.holes || [];
  50015. var depth = options.depth || 0;
  50016. var contours = [];
  50017. var hole = [];
  50018. for (var i = 0; i < shape.length; i++) {
  50019. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50020. }
  50021. var epsilon = 0.00000001;
  50022. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50023. contours.pop();
  50024. }
  50025. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50026. for (var hNb = 0; hNb < holes.length; hNb++) {
  50027. hole = [];
  50028. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50029. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50030. }
  50031. polygonTriangulation.addHole(hole);
  50032. }
  50033. var polygon = polygonTriangulation.build(options.updatable, depth);
  50034. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50035. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50036. vertexData.applyToMesh(polygon, options.updatable);
  50037. return polygon;
  50038. };
  50039. ;
  50040. /**
  50041. * Creates an extruded polygon mesh, with depth in the Y direction.
  50042. * 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).
  50043. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50044. */
  50045. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50046. return MeshBuilder.CreatePolygon(name, options, scene);
  50047. };
  50048. ;
  50049. /**
  50050. * Creates a tube mesh.
  50051. * 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.
  50052. *
  50053. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50054. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50055. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50056. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50057. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50058. * 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.
  50059. * It must return a radius value (positive float) :
  50060. * ```javascript
  50061. * var radiusFunction = function(i, distance) {
  50062. * // do things
  50063. * return radius; }
  50064. * ```
  50065. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50066. * 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
  50067. * 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
  50068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50069. * 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).
  50070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50071. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50073. */
  50074. MeshBuilder.CreateTube = function (name, options, scene) {
  50075. var path = options.path;
  50076. var instance = options.instance;
  50077. var radius = 1.0;
  50078. if (instance) {
  50079. radius = instance.radius;
  50080. }
  50081. if (options.radius !== undefined) {
  50082. radius = options.radius;
  50083. }
  50084. ;
  50085. var tessellation = options.tessellation || 64 | 0;
  50086. var radiusFunction = options.radiusFunction || null;
  50087. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50088. var invertUV = options.invertUV || false;
  50089. var updatable = options.updatable;
  50090. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50091. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50092. // tube geometry
  50093. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50094. var tangents = path3D.getTangents();
  50095. var normals = path3D.getNormals();
  50096. var distances = path3D.getDistances();
  50097. var pi2 = Math.PI * 2;
  50098. var step = pi2 / tessellation * arc;
  50099. var returnRadius = function () { return radius; };
  50100. var radiusFunctionFinal = radiusFunction || returnRadius;
  50101. var circlePath;
  50102. var rad;
  50103. var normal;
  50104. var rotated;
  50105. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50106. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50107. for (var i = 0; i < path.length; i++) {
  50108. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50109. circlePath = Array(); // current circle array
  50110. normal = normals[i]; // current normal
  50111. for (var t = 0; t < tessellation; t++) {
  50112. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50113. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50114. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50115. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50116. circlePath[t] = rotated;
  50117. }
  50118. circlePaths[index] = circlePath;
  50119. index++;
  50120. }
  50121. // cap
  50122. var capPath = function (nbPoints, pathIndex) {
  50123. var pointCap = Array();
  50124. for (var i = 0; i < nbPoints; i++) {
  50125. pointCap.push(path[pathIndex]);
  50126. }
  50127. return pointCap;
  50128. };
  50129. switch (cap) {
  50130. case BABYLON.Mesh.NO_CAP:
  50131. break;
  50132. case BABYLON.Mesh.CAP_START:
  50133. circlePaths[0] = capPath(tessellation, 0);
  50134. circlePaths[1] = circlePaths[2].slice(0);
  50135. break;
  50136. case BABYLON.Mesh.CAP_END:
  50137. circlePaths[index] = circlePaths[index - 1].slice(0);
  50138. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50139. break;
  50140. case BABYLON.Mesh.CAP_ALL:
  50141. circlePaths[0] = capPath(tessellation, 0);
  50142. circlePaths[1] = circlePaths[2].slice(0);
  50143. circlePaths[index] = circlePaths[index - 1].slice(0);
  50144. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50145. break;
  50146. default:
  50147. break;
  50148. }
  50149. return circlePaths;
  50150. };
  50151. var path3D;
  50152. var pathArray;
  50153. if (instance) {
  50154. var arc = options.arc || instance.arc;
  50155. path3D = (instance.path3D).update(path);
  50156. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50157. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50158. instance.path3D = path3D;
  50159. instance.pathArray = pathArray;
  50160. instance.arc = arc;
  50161. instance.radius = radius;
  50162. return instance;
  50163. }
  50164. // tube creation
  50165. path3D = new BABYLON.Path3D(path);
  50166. var newPathArray = new Array();
  50167. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50168. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50169. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50170. tube.pathArray = pathArray;
  50171. tube.path3D = path3D;
  50172. tube.tessellation = tessellation;
  50173. tube.cap = cap;
  50174. tube.arc = options.arc;
  50175. tube.radius = radius;
  50176. return tube;
  50177. };
  50178. /**
  50179. * Creates a polyhedron mesh.
  50180. *
  50181. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50182. * 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
  50183. * to choose the wanted type.
  50184. * The parameter `size` (positive float, default 1) sets the polygon size.
  50185. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50186. * 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`.
  50187. * 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
  50188. * 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)`).
  50189. * 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
  50190. * 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.
  50191. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50192. * 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).
  50193. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50194. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50195. */
  50196. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50197. var polyhedron = new BABYLON.Mesh(name, scene);
  50198. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50199. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50200. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50201. vertexData.applyToMesh(polyhedron, options.updatable);
  50202. return polyhedron;
  50203. };
  50204. /**
  50205. * Creates a decal mesh.
  50206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50207. * 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.
  50208. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50209. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50210. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50211. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50212. */
  50213. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50214. var indices = sourceMesh.getIndices();
  50215. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50216. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50217. var position = options.position || BABYLON.Vector3.Zero();
  50218. var normal = options.normal || BABYLON.Vector3.Up();
  50219. var size = options.size || BABYLON.Vector3.One();
  50220. var angle = options.angle || 0;
  50221. // Getting correct rotation
  50222. if (!normal) {
  50223. var target = new BABYLON.Vector3(0, 0, 1);
  50224. var camera = sourceMesh.getScene().activeCamera;
  50225. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50226. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50227. }
  50228. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50229. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50230. var pitch = Math.atan2(normal.y, len);
  50231. // Matrix
  50232. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50233. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50234. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50235. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50236. var vertexData = new BABYLON.VertexData();
  50237. vertexData.indices = [];
  50238. vertexData.positions = [];
  50239. vertexData.normals = [];
  50240. vertexData.uvs = [];
  50241. var currentVertexDataIndex = 0;
  50242. var extractDecalVector3 = function (indexId) {
  50243. var result = new BABYLON.PositionNormalVertex();
  50244. if (!indices || !positions || !normals) {
  50245. return result;
  50246. }
  50247. var vertexId = indices[indexId];
  50248. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50249. // Send vector to decal local world
  50250. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50251. // Get normal
  50252. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50253. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50254. return result;
  50255. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50256. var clip = function (vertices, axis) {
  50257. if (vertices.length === 0) {
  50258. return vertices;
  50259. }
  50260. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50261. var clipVertices = function (v0, v1) {
  50262. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50263. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50264. };
  50265. var result = new Array();
  50266. for (var index = 0; index < vertices.length; index += 3) {
  50267. var v1Out;
  50268. var v2Out;
  50269. var v3Out;
  50270. var total = 0;
  50271. var nV1 = null;
  50272. var nV2 = null;
  50273. var nV3 = null;
  50274. var nV4 = null;
  50275. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50276. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50277. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50278. v1Out = d1 > 0;
  50279. v2Out = d2 > 0;
  50280. v3Out = d3 > 0;
  50281. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50282. switch (total) {
  50283. case 0:
  50284. result.push(vertices[index]);
  50285. result.push(vertices[index + 1]);
  50286. result.push(vertices[index + 2]);
  50287. break;
  50288. case 1:
  50289. if (v1Out) {
  50290. nV1 = vertices[index + 1];
  50291. nV2 = vertices[index + 2];
  50292. nV3 = clipVertices(vertices[index], nV1);
  50293. nV4 = clipVertices(vertices[index], nV2);
  50294. }
  50295. if (v2Out) {
  50296. nV1 = vertices[index];
  50297. nV2 = vertices[index + 2];
  50298. nV3 = clipVertices(vertices[index + 1], nV1);
  50299. nV4 = clipVertices(vertices[index + 1], nV2);
  50300. result.push(nV3);
  50301. result.push(nV2.clone());
  50302. result.push(nV1.clone());
  50303. result.push(nV2.clone());
  50304. result.push(nV3.clone());
  50305. result.push(nV4);
  50306. break;
  50307. }
  50308. if (v3Out) {
  50309. nV1 = vertices[index];
  50310. nV2 = vertices[index + 1];
  50311. nV3 = clipVertices(vertices[index + 2], nV1);
  50312. nV4 = clipVertices(vertices[index + 2], nV2);
  50313. }
  50314. if (nV1 && nV2 && nV3 && nV4) {
  50315. result.push(nV1.clone());
  50316. result.push(nV2.clone());
  50317. result.push(nV3);
  50318. result.push(nV4);
  50319. result.push(nV3.clone());
  50320. result.push(nV2.clone());
  50321. }
  50322. break;
  50323. case 2:
  50324. if (!v1Out) {
  50325. nV1 = vertices[index].clone();
  50326. nV2 = clipVertices(nV1, vertices[index + 1]);
  50327. nV3 = clipVertices(nV1, vertices[index + 2]);
  50328. result.push(nV1);
  50329. result.push(nV2);
  50330. result.push(nV3);
  50331. }
  50332. if (!v2Out) {
  50333. nV1 = vertices[index + 1].clone();
  50334. nV2 = clipVertices(nV1, vertices[index + 2]);
  50335. nV3 = clipVertices(nV1, vertices[index]);
  50336. result.push(nV1);
  50337. result.push(nV2);
  50338. result.push(nV3);
  50339. }
  50340. if (!v3Out) {
  50341. nV1 = vertices[index + 2].clone();
  50342. nV2 = clipVertices(nV1, vertices[index]);
  50343. nV3 = clipVertices(nV1, vertices[index + 1]);
  50344. result.push(nV1);
  50345. result.push(nV2);
  50346. result.push(nV3);
  50347. }
  50348. break;
  50349. case 3:
  50350. break;
  50351. }
  50352. }
  50353. return result;
  50354. };
  50355. for (var index = 0; index < indices.length; index += 3) {
  50356. var faceVertices = new Array();
  50357. faceVertices.push(extractDecalVector3(index));
  50358. faceVertices.push(extractDecalVector3(index + 1));
  50359. faceVertices.push(extractDecalVector3(index + 2));
  50360. // Clip
  50361. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50362. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50363. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50364. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50365. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50366. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50367. if (faceVertices.length === 0) {
  50368. continue;
  50369. }
  50370. // Add UVs and get back to world
  50371. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50372. var vertex = faceVertices[vIndex];
  50373. //TODO check for Int32Array | Uint32Array | Uint16Array
  50374. vertexData.indices.push(currentVertexDataIndex);
  50375. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50376. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50377. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50378. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50379. currentVertexDataIndex++;
  50380. }
  50381. }
  50382. // Return mesh
  50383. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50384. vertexData.applyToMesh(decal);
  50385. decal.position = position.clone();
  50386. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50387. return decal;
  50388. };
  50389. // Privates
  50390. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50391. // extrusion geometry
  50392. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50393. var tangents = path3D.getTangents();
  50394. var normals = path3D.getNormals();
  50395. var binormals = path3D.getBinormals();
  50396. var distances = path3D.getDistances();
  50397. var angle = 0;
  50398. var returnScale = function () { return scale !== null ? scale : 1; };
  50399. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50400. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50401. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50402. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50403. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50404. for (var i = 0; i < curve.length; i++) {
  50405. var shapePath = new Array();
  50406. var angleStep = rotate(i, distances[i]);
  50407. var scaleRatio = scl(i, distances[i]);
  50408. for (var p = 0; p < shape.length; p++) {
  50409. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50410. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50411. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50412. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50413. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50414. shapePath[p] = rotated;
  50415. }
  50416. shapePaths[index] = shapePath;
  50417. angle += angleStep;
  50418. index++;
  50419. }
  50420. // cap
  50421. var capPath = function (shapePath) {
  50422. var pointCap = Array();
  50423. var barycenter = BABYLON.Vector3.Zero();
  50424. var i;
  50425. for (i = 0; i < shapePath.length; i++) {
  50426. barycenter.addInPlace(shapePath[i]);
  50427. }
  50428. barycenter.scaleInPlace(1.0 / shapePath.length);
  50429. for (i = 0; i < shapePath.length; i++) {
  50430. pointCap.push(barycenter);
  50431. }
  50432. return pointCap;
  50433. };
  50434. switch (cap) {
  50435. case BABYLON.Mesh.NO_CAP:
  50436. break;
  50437. case BABYLON.Mesh.CAP_START:
  50438. shapePaths[0] = capPath(shapePaths[2]);
  50439. shapePaths[1] = shapePaths[2];
  50440. break;
  50441. case BABYLON.Mesh.CAP_END:
  50442. shapePaths[index] = shapePaths[index - 1];
  50443. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50444. break;
  50445. case BABYLON.Mesh.CAP_ALL:
  50446. shapePaths[0] = capPath(shapePaths[2]);
  50447. shapePaths[1] = shapePaths[2];
  50448. shapePaths[index] = shapePaths[index - 1];
  50449. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50450. break;
  50451. default:
  50452. break;
  50453. }
  50454. return shapePaths;
  50455. };
  50456. var path3D;
  50457. var pathArray;
  50458. if (instance) {
  50459. path3D = (instance.path3D).update(curve);
  50460. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50461. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50462. return instance;
  50463. }
  50464. // extruded shape creation
  50465. path3D = new BABYLON.Path3D(curve);
  50466. var newShapePaths = new Array();
  50467. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50468. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50469. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50470. extrudedGeneric.pathArray = pathArray;
  50471. extrudedGeneric.path3D = path3D;
  50472. extrudedGeneric.cap = cap;
  50473. return extrudedGeneric;
  50474. };
  50475. return MeshBuilder;
  50476. }());
  50477. BABYLON.MeshBuilder = MeshBuilder;
  50478. })(BABYLON || (BABYLON = {}));
  50479. //# sourceMappingURL=babylon.meshBuilder.js.map
  50480. var BABYLON;
  50481. (function (BABYLON) {
  50482. var AudioEngine = /** @class */ (function () {
  50483. function AudioEngine() {
  50484. this._audioContext = null;
  50485. this._audioContextInitialized = false;
  50486. this.canUseWebAudio = false;
  50487. this.WarnedWebAudioUnsupported = false;
  50488. this.unlocked = false;
  50489. this.isMP3supported = false;
  50490. this.isOGGsupported = false;
  50491. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50492. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50493. this.canUseWebAudio = true;
  50494. }
  50495. var audioElem = document.createElement('audio');
  50496. try {
  50497. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50498. this.isMP3supported = true;
  50499. }
  50500. }
  50501. catch (e) {
  50502. // protect error during capability check.
  50503. }
  50504. try {
  50505. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50506. this.isOGGsupported = true;
  50507. }
  50508. }
  50509. catch (e) {
  50510. // protect error during capability check.
  50511. }
  50512. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50513. this._unlockiOSaudio();
  50514. }
  50515. else {
  50516. this.unlocked = true;
  50517. }
  50518. }
  50519. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50520. get: function () {
  50521. if (!this._audioContextInitialized) {
  50522. this._initializeAudioContext();
  50523. }
  50524. return this._audioContext;
  50525. },
  50526. enumerable: true,
  50527. configurable: true
  50528. });
  50529. AudioEngine.prototype._unlockiOSaudio = function () {
  50530. var _this = this;
  50531. var unlockaudio = function () {
  50532. if (!_this.audioContext) {
  50533. return;
  50534. }
  50535. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50536. var source = _this.audioContext.createBufferSource();
  50537. source.buffer = buffer;
  50538. source.connect(_this.audioContext.destination);
  50539. source.start(0);
  50540. setTimeout(function () {
  50541. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50542. _this.unlocked = true;
  50543. window.removeEventListener('touchend', unlockaudio, false);
  50544. if (_this.onAudioUnlocked) {
  50545. _this.onAudioUnlocked();
  50546. }
  50547. }
  50548. }, 0);
  50549. };
  50550. window.addEventListener('touchend', unlockaudio, false);
  50551. };
  50552. AudioEngine.prototype._initializeAudioContext = function () {
  50553. try {
  50554. if (this.canUseWebAudio) {
  50555. this._audioContext = new AudioContext();
  50556. // create a global volume gain node
  50557. this.masterGain = this._audioContext.createGain();
  50558. this.masterGain.gain.value = 1;
  50559. this.masterGain.connect(this._audioContext.destination);
  50560. this._audioContextInitialized = true;
  50561. }
  50562. }
  50563. catch (e) {
  50564. this.canUseWebAudio = false;
  50565. BABYLON.Tools.Error("Web Audio: " + e.message);
  50566. }
  50567. };
  50568. AudioEngine.prototype.dispose = function () {
  50569. if (this.canUseWebAudio && this._audioContextInitialized) {
  50570. if (this._connectedAnalyser && this._audioContext) {
  50571. this._connectedAnalyser.stopDebugCanvas();
  50572. this._connectedAnalyser.dispose();
  50573. this.masterGain.disconnect();
  50574. this.masterGain.connect(this._audioContext.destination);
  50575. this._connectedAnalyser = null;
  50576. }
  50577. this.masterGain.gain.value = 1;
  50578. }
  50579. this.WarnedWebAudioUnsupported = false;
  50580. };
  50581. AudioEngine.prototype.getGlobalVolume = function () {
  50582. if (this.canUseWebAudio && this._audioContextInitialized) {
  50583. return this.masterGain.gain.value;
  50584. }
  50585. else {
  50586. return -1;
  50587. }
  50588. };
  50589. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50590. if (this.canUseWebAudio && this._audioContextInitialized) {
  50591. this.masterGain.gain.value = newVolume;
  50592. }
  50593. };
  50594. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50595. if (this._connectedAnalyser) {
  50596. this._connectedAnalyser.stopDebugCanvas();
  50597. }
  50598. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50599. this._connectedAnalyser = analyser;
  50600. this.masterGain.disconnect();
  50601. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50602. }
  50603. };
  50604. return AudioEngine;
  50605. }());
  50606. BABYLON.AudioEngine = AudioEngine;
  50607. })(BABYLON || (BABYLON = {}));
  50608. //# sourceMappingURL=babylon.audioEngine.js.map
  50609. var BABYLON;
  50610. (function (BABYLON) {
  50611. var Sound = /** @class */ (function () {
  50612. /**
  50613. * Create a sound and attach it to a scene
  50614. * @param name Name of your sound
  50615. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50616. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50617. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50618. */
  50619. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50620. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50621. var _this = this;
  50622. this.autoplay = false;
  50623. this.loop = false;
  50624. this.useCustomAttenuation = false;
  50625. this.spatialSound = false;
  50626. this.refDistance = 1;
  50627. this.rolloffFactor = 1;
  50628. this.maxDistance = 100;
  50629. this.distanceModel = "linear";
  50630. this._panningModel = "equalpower";
  50631. this._playbackRate = 1;
  50632. this._streaming = false;
  50633. this._startTime = 0;
  50634. this._startOffset = 0;
  50635. this._position = BABYLON.Vector3.Zero();
  50636. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50637. this._volume = 1;
  50638. this._isReadyToPlay = false;
  50639. this.isPlaying = false;
  50640. this.isPaused = false;
  50641. this._isDirectional = false;
  50642. // Used if you'd like to create a directional sound.
  50643. // If not set, the sound will be omnidirectional
  50644. this._coneInnerAngle = 360;
  50645. this._coneOuterAngle = 360;
  50646. this._coneOuterGain = 0;
  50647. this._isOutputConnected = false;
  50648. this._urlType = "Unknown";
  50649. this.name = name;
  50650. this._scene = scene;
  50651. this._readyToPlayCallback = readyToPlayCallback;
  50652. // Default custom attenuation function is a linear attenuation
  50653. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50654. if (currentDistance < maxDistance) {
  50655. return currentVolume * (1 - currentDistance / maxDistance);
  50656. }
  50657. else {
  50658. return 0;
  50659. }
  50660. };
  50661. if (options) {
  50662. this.autoplay = options.autoplay || false;
  50663. this.loop = options.loop || false;
  50664. // if volume === 0, we need another way to check this option
  50665. if (options.volume !== undefined) {
  50666. this._volume = options.volume;
  50667. }
  50668. this.spatialSound = options.spatialSound || false;
  50669. this.maxDistance = options.maxDistance || 100;
  50670. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50671. this.rolloffFactor = options.rolloffFactor || 1;
  50672. this.refDistance = options.refDistance || 1;
  50673. this.distanceModel = options.distanceModel || "linear";
  50674. this._playbackRate = options.playbackRate || 1;
  50675. this._streaming = options.streaming || false;
  50676. }
  50677. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50678. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50679. this._soundGain.gain.value = this._volume;
  50680. this._inputAudioNode = this._soundGain;
  50681. this._ouputAudioNode = this._soundGain;
  50682. if (this.spatialSound) {
  50683. this._createSpatialParameters();
  50684. }
  50685. this._scene.mainSoundTrack.AddSound(this);
  50686. var validParameter = true;
  50687. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50688. if (urlOrArrayBuffer) {
  50689. if (typeof (urlOrArrayBuffer) === "string")
  50690. this._urlType = "String";
  50691. if (Array.isArray(urlOrArrayBuffer))
  50692. this._urlType = "Array";
  50693. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50694. this._urlType = "ArrayBuffer";
  50695. var urls = [];
  50696. var codecSupportedFound = false;
  50697. switch (this._urlType) {
  50698. case "ArrayBuffer":
  50699. if (urlOrArrayBuffer.byteLength > 0) {
  50700. codecSupportedFound = true;
  50701. this._soundLoaded(urlOrArrayBuffer);
  50702. }
  50703. break;
  50704. case "String":
  50705. urls.push(urlOrArrayBuffer);
  50706. case "Array":
  50707. if (urls.length === 0)
  50708. urls = urlOrArrayBuffer;
  50709. // If we found a supported format, we load it immediately and stop the loop
  50710. for (var i = 0; i < urls.length; i++) {
  50711. var url = urls[i];
  50712. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50713. codecSupportedFound = true;
  50714. }
  50715. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50716. codecSupportedFound = true;
  50717. }
  50718. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50719. codecSupportedFound = true;
  50720. }
  50721. if (url.indexOf("blob:") !== -1) {
  50722. codecSupportedFound = true;
  50723. }
  50724. if (codecSupportedFound) {
  50725. // Loading sound using XHR2
  50726. if (!this._streaming) {
  50727. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50728. }
  50729. else {
  50730. this._htmlAudioElement = new Audio(url);
  50731. this._htmlAudioElement.controls = false;
  50732. this._htmlAudioElement.loop = this.loop;
  50733. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50734. this._htmlAudioElement.preload = "auto";
  50735. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50736. _this._isReadyToPlay = true;
  50737. if (_this.autoplay) {
  50738. _this.play();
  50739. }
  50740. if (_this._readyToPlayCallback) {
  50741. _this._readyToPlayCallback();
  50742. }
  50743. });
  50744. document.body.appendChild(this._htmlAudioElement);
  50745. }
  50746. break;
  50747. }
  50748. }
  50749. break;
  50750. default:
  50751. validParameter = false;
  50752. break;
  50753. }
  50754. if (!validParameter) {
  50755. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50756. }
  50757. else {
  50758. if (!codecSupportedFound) {
  50759. this._isReadyToPlay = true;
  50760. // Simulating a ready to play event to avoid breaking code path
  50761. if (this._readyToPlayCallback) {
  50762. window.setTimeout(function () {
  50763. if (_this._readyToPlayCallback) {
  50764. _this._readyToPlayCallback();
  50765. }
  50766. }, 1000);
  50767. }
  50768. }
  50769. }
  50770. }
  50771. }
  50772. else {
  50773. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50774. this._scene.mainSoundTrack.AddSound(this);
  50775. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50776. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50777. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50778. }
  50779. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50780. if (this._readyToPlayCallback) {
  50781. window.setTimeout(function () {
  50782. if (_this._readyToPlayCallback) {
  50783. _this._readyToPlayCallback();
  50784. }
  50785. }, 1000);
  50786. }
  50787. }
  50788. }
  50789. Sound.prototype.dispose = function () {
  50790. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50791. if (this.isPlaying) {
  50792. this.stop();
  50793. }
  50794. this._isReadyToPlay = false;
  50795. if (this.soundTrackId === -1) {
  50796. this._scene.mainSoundTrack.RemoveSound(this);
  50797. }
  50798. else {
  50799. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50800. }
  50801. if (this._soundGain) {
  50802. this._soundGain.disconnect();
  50803. this._soundGain = null;
  50804. }
  50805. if (this._soundPanner) {
  50806. this._soundPanner.disconnect();
  50807. this._soundPanner = null;
  50808. }
  50809. if (this._soundSource) {
  50810. this._soundSource.disconnect();
  50811. this._soundSource = null;
  50812. }
  50813. this._audioBuffer = null;
  50814. if (this._htmlAudioElement) {
  50815. this._htmlAudioElement.pause();
  50816. this._htmlAudioElement.src = "";
  50817. document.body.removeChild(this._htmlAudioElement);
  50818. }
  50819. if (this._connectedMesh && this._registerFunc) {
  50820. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50821. this._connectedMesh = null;
  50822. }
  50823. }
  50824. };
  50825. Sound.prototype.isReady = function () {
  50826. return this._isReadyToPlay;
  50827. };
  50828. Sound.prototype._soundLoaded = function (audioData) {
  50829. var _this = this;
  50830. if (!BABYLON.Engine.audioEngine.audioContext) {
  50831. return;
  50832. }
  50833. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50834. _this._audioBuffer = buffer;
  50835. _this._isReadyToPlay = true;
  50836. if (_this.autoplay) {
  50837. _this.play();
  50838. }
  50839. if (_this._readyToPlayCallback) {
  50840. _this._readyToPlayCallback();
  50841. }
  50842. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50843. };
  50844. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50845. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50846. this._audioBuffer = audioBuffer;
  50847. this._isReadyToPlay = true;
  50848. }
  50849. };
  50850. Sound.prototype.updateOptions = function (options) {
  50851. if (options) {
  50852. this.loop = options.loop || this.loop;
  50853. this.maxDistance = options.maxDistance || this.maxDistance;
  50854. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50855. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50856. this.refDistance = options.refDistance || this.refDistance;
  50857. this.distanceModel = options.distanceModel || this.distanceModel;
  50858. this._playbackRate = options.playbackRate || this._playbackRate;
  50859. this._updateSpatialParameters();
  50860. if (this.isPlaying) {
  50861. if (this._streaming) {
  50862. this._htmlAudioElement.playbackRate = this._playbackRate;
  50863. }
  50864. else {
  50865. if (this._soundSource) {
  50866. this._soundSource.playbackRate.value = this._playbackRate;
  50867. }
  50868. }
  50869. }
  50870. }
  50871. };
  50872. Sound.prototype._createSpatialParameters = function () {
  50873. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50874. if (this._scene.headphone) {
  50875. this._panningModel = "HRTF";
  50876. }
  50877. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50878. this._updateSpatialParameters();
  50879. this._soundPanner.connect(this._ouputAudioNode);
  50880. this._inputAudioNode = this._soundPanner;
  50881. }
  50882. };
  50883. Sound.prototype._updateSpatialParameters = function () {
  50884. if (this.spatialSound && this._soundPanner) {
  50885. if (this.useCustomAttenuation) {
  50886. // Tricks to disable in a way embedded Web Audio attenuation
  50887. this._soundPanner.distanceModel = "linear";
  50888. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50889. this._soundPanner.refDistance = 1;
  50890. this._soundPanner.rolloffFactor = 1;
  50891. this._soundPanner.panningModel = this._panningModel;
  50892. }
  50893. else {
  50894. this._soundPanner.distanceModel = this.distanceModel;
  50895. this._soundPanner.maxDistance = this.maxDistance;
  50896. this._soundPanner.refDistance = this.refDistance;
  50897. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50898. this._soundPanner.panningModel = this._panningModel;
  50899. }
  50900. }
  50901. };
  50902. Sound.prototype.switchPanningModelToHRTF = function () {
  50903. this._panningModel = "HRTF";
  50904. this._switchPanningModel();
  50905. };
  50906. Sound.prototype.switchPanningModelToEqualPower = function () {
  50907. this._panningModel = "equalpower";
  50908. this._switchPanningModel();
  50909. };
  50910. Sound.prototype._switchPanningModel = function () {
  50911. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50912. this._soundPanner.panningModel = this._panningModel;
  50913. }
  50914. };
  50915. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50916. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50917. if (this._isOutputConnected) {
  50918. this._ouputAudioNode.disconnect();
  50919. }
  50920. this._ouputAudioNode.connect(soundTrackAudioNode);
  50921. this._isOutputConnected = true;
  50922. }
  50923. };
  50924. /**
  50925. * Transform this sound into a directional source
  50926. * @param coneInnerAngle Size of the inner cone in degree
  50927. * @param coneOuterAngle Size of the outer cone in degree
  50928. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50929. */
  50930. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50931. if (coneOuterAngle < coneInnerAngle) {
  50932. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50933. return;
  50934. }
  50935. this._coneInnerAngle = coneInnerAngle;
  50936. this._coneOuterAngle = coneOuterAngle;
  50937. this._coneOuterGain = coneOuterGain;
  50938. this._isDirectional = true;
  50939. if (this.isPlaying && this.loop) {
  50940. this.stop();
  50941. this.play();
  50942. }
  50943. };
  50944. Sound.prototype.setPosition = function (newPosition) {
  50945. this._position = newPosition;
  50946. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50947. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50948. }
  50949. };
  50950. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50951. this._localDirection = newLocalDirection;
  50952. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50953. this._updateDirection();
  50954. }
  50955. };
  50956. Sound.prototype._updateDirection = function () {
  50957. if (!this._connectedMesh || !this._soundPanner) {
  50958. return;
  50959. }
  50960. var mat = this._connectedMesh.getWorldMatrix();
  50961. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50962. direction.normalize();
  50963. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50964. };
  50965. Sound.prototype.updateDistanceFromListener = function () {
  50966. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50967. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50968. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50969. }
  50970. };
  50971. Sound.prototype.setAttenuationFunction = function (callback) {
  50972. this._customAttenuationFunction = callback;
  50973. };
  50974. /**
  50975. * Play the sound
  50976. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50977. * @param offset (optional) Start the sound setting it at a specific time
  50978. */
  50979. Sound.prototype.play = function (time, offset) {
  50980. var _this = this;
  50981. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50982. try {
  50983. if (this._startOffset < 0) {
  50984. time = -this._startOffset;
  50985. this._startOffset = 0;
  50986. }
  50987. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50988. if (!this._soundSource || !this._streamingSource) {
  50989. if (this.spatialSound && this._soundPanner) {
  50990. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50991. if (this._isDirectional) {
  50992. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50993. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50994. this._soundPanner.coneOuterGain = this._coneOuterGain;
  50995. if (this._connectedMesh) {
  50996. this._updateDirection();
  50997. }
  50998. else {
  50999. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51000. }
  51001. }
  51002. }
  51003. }
  51004. if (this._streaming) {
  51005. if (!this._streamingSource) {
  51006. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51007. this._htmlAudioElement.onended = function () { _this._onended(); };
  51008. this._htmlAudioElement.playbackRate = this._playbackRate;
  51009. }
  51010. this._streamingSource.disconnect();
  51011. this._streamingSource.connect(this._inputAudioNode);
  51012. this._htmlAudioElement.play();
  51013. }
  51014. else {
  51015. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51016. this._soundSource.buffer = this._audioBuffer;
  51017. this._soundSource.connect(this._inputAudioNode);
  51018. this._soundSource.loop = this.loop;
  51019. this._soundSource.playbackRate.value = this._playbackRate;
  51020. this._soundSource.onended = function () { _this._onended(); };
  51021. if (this._soundSource.buffer) {
  51022. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51023. }
  51024. }
  51025. this._startTime = startTime;
  51026. this.isPlaying = true;
  51027. this.isPaused = false;
  51028. }
  51029. catch (ex) {
  51030. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51031. }
  51032. }
  51033. };
  51034. Sound.prototype._onended = function () {
  51035. this.isPlaying = false;
  51036. if (this.onended) {
  51037. this.onended();
  51038. }
  51039. };
  51040. /**
  51041. * Stop the sound
  51042. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51043. */
  51044. Sound.prototype.stop = function (time) {
  51045. if (this.isPlaying) {
  51046. if (this._streaming) {
  51047. this._htmlAudioElement.pause();
  51048. // Test needed for Firefox or it will generate an Invalid State Error
  51049. if (this._htmlAudioElement.currentTime > 0) {
  51050. this._htmlAudioElement.currentTime = 0;
  51051. }
  51052. }
  51053. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51054. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51055. this._soundSource.stop(stopTime);
  51056. this._soundSource.onended = function () { };
  51057. if (!this.isPaused) {
  51058. this._startOffset = 0;
  51059. }
  51060. }
  51061. this.isPlaying = false;
  51062. }
  51063. };
  51064. Sound.prototype.pause = function () {
  51065. if (this.isPlaying) {
  51066. this.isPaused = true;
  51067. if (this._streaming) {
  51068. this._htmlAudioElement.pause();
  51069. }
  51070. else if (BABYLON.Engine.audioEngine.audioContext) {
  51071. this.stop(0);
  51072. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51073. }
  51074. }
  51075. };
  51076. Sound.prototype.setVolume = function (newVolume, time) {
  51077. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51078. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51079. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51080. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51081. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51082. }
  51083. else {
  51084. this._soundGain.gain.value = newVolume;
  51085. }
  51086. }
  51087. this._volume = newVolume;
  51088. };
  51089. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51090. this._playbackRate = newPlaybackRate;
  51091. if (this.isPlaying) {
  51092. if (this._streaming) {
  51093. this._htmlAudioElement.playbackRate = this._playbackRate;
  51094. }
  51095. else if (this._soundSource) {
  51096. this._soundSource.playbackRate.value = this._playbackRate;
  51097. }
  51098. }
  51099. };
  51100. Sound.prototype.getVolume = function () {
  51101. return this._volume;
  51102. };
  51103. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51104. var _this = this;
  51105. if (this._connectedMesh && this._registerFunc) {
  51106. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51107. this._registerFunc = null;
  51108. }
  51109. this._connectedMesh = meshToConnectTo;
  51110. if (!this.spatialSound) {
  51111. this.spatialSound = true;
  51112. this._createSpatialParameters();
  51113. if (this.isPlaying && this.loop) {
  51114. this.stop();
  51115. this.play();
  51116. }
  51117. }
  51118. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51119. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51120. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51121. };
  51122. Sound.prototype.detachFromMesh = function () {
  51123. if (this._connectedMesh && this._registerFunc) {
  51124. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51125. this._registerFunc = null;
  51126. this._connectedMesh = null;
  51127. }
  51128. };
  51129. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51130. if (!node.getBoundingInfo) {
  51131. return;
  51132. }
  51133. var mesh = node;
  51134. var boundingInfo = mesh.getBoundingInfo();
  51135. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51136. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51137. this._updateDirection();
  51138. }
  51139. };
  51140. Sound.prototype.clone = function () {
  51141. var _this = this;
  51142. if (!this._streaming) {
  51143. var setBufferAndRun = function () {
  51144. if (_this._isReadyToPlay) {
  51145. clonedSound._audioBuffer = _this.getAudioBuffer();
  51146. clonedSound._isReadyToPlay = true;
  51147. if (clonedSound.autoplay) {
  51148. clonedSound.play();
  51149. }
  51150. }
  51151. else {
  51152. window.setTimeout(setBufferAndRun, 300);
  51153. }
  51154. };
  51155. var currentOptions = {
  51156. autoplay: this.autoplay, loop: this.loop,
  51157. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51158. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51159. refDistance: this.refDistance, distanceModel: this.distanceModel
  51160. };
  51161. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51162. if (this.useCustomAttenuation) {
  51163. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51164. }
  51165. clonedSound.setPosition(this._position);
  51166. clonedSound.setPlaybackRate(this._playbackRate);
  51167. setBufferAndRun();
  51168. return clonedSound;
  51169. }
  51170. else {
  51171. return null;
  51172. }
  51173. };
  51174. Sound.prototype.getAudioBuffer = function () {
  51175. return this._audioBuffer;
  51176. };
  51177. Sound.prototype.serialize = function () {
  51178. var serializationObject = {
  51179. name: this.name,
  51180. url: this.name,
  51181. autoplay: this.autoplay,
  51182. loop: this.loop,
  51183. volume: this._volume,
  51184. spatialSound: this.spatialSound,
  51185. maxDistance: this.maxDistance,
  51186. rolloffFactor: this.rolloffFactor,
  51187. refDistance: this.refDistance,
  51188. distanceModel: this.distanceModel,
  51189. playbackRate: this._playbackRate,
  51190. panningModel: this._panningModel,
  51191. soundTrackId: this.soundTrackId
  51192. };
  51193. if (this.spatialSound) {
  51194. if (this._connectedMesh)
  51195. serializationObject.connectedMeshId = this._connectedMesh.id;
  51196. serializationObject.position = this._position.asArray();
  51197. serializationObject.refDistance = this.refDistance;
  51198. serializationObject.distanceModel = this.distanceModel;
  51199. serializationObject.isDirectional = this._isDirectional;
  51200. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51201. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51202. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51203. serializationObject.coneOuterGain = this._coneOuterGain;
  51204. }
  51205. return serializationObject;
  51206. };
  51207. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51208. var soundName = parsedSound.name;
  51209. var soundUrl;
  51210. if (parsedSound.url) {
  51211. soundUrl = rootUrl + parsedSound.url;
  51212. }
  51213. else {
  51214. soundUrl = rootUrl + soundName;
  51215. }
  51216. var options = {
  51217. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51218. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51219. rolloffFactor: parsedSound.rolloffFactor,
  51220. refDistance: parsedSound.refDistance,
  51221. distanceModel: parsedSound.distanceModel,
  51222. playbackRate: parsedSound.playbackRate
  51223. };
  51224. var newSound;
  51225. if (!sourceSound) {
  51226. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51227. scene._addPendingData(newSound);
  51228. }
  51229. else {
  51230. var setBufferAndRun = function () {
  51231. if (sourceSound._isReadyToPlay) {
  51232. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51233. newSound._isReadyToPlay = true;
  51234. if (newSound.autoplay) {
  51235. newSound.play();
  51236. }
  51237. }
  51238. else {
  51239. window.setTimeout(setBufferAndRun, 300);
  51240. }
  51241. };
  51242. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51243. setBufferAndRun();
  51244. }
  51245. if (parsedSound.position) {
  51246. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51247. newSound.setPosition(soundPosition);
  51248. }
  51249. if (parsedSound.isDirectional) {
  51250. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51251. if (parsedSound.localDirectionToMesh) {
  51252. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51253. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51254. }
  51255. }
  51256. if (parsedSound.connectedMeshId) {
  51257. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51258. if (connectedMesh) {
  51259. newSound.attachToMesh(connectedMesh);
  51260. }
  51261. }
  51262. return newSound;
  51263. };
  51264. return Sound;
  51265. }());
  51266. BABYLON.Sound = Sound;
  51267. })(BABYLON || (BABYLON = {}));
  51268. //# sourceMappingURL=babylon.sound.js.map
  51269. var BABYLON;
  51270. (function (BABYLON) {
  51271. var SoundTrack = /** @class */ (function () {
  51272. function SoundTrack(scene, options) {
  51273. this.id = -1;
  51274. this._isMainTrack = false;
  51275. this._isInitialized = false;
  51276. this._scene = scene;
  51277. this.soundCollection = new Array();
  51278. this._options = options;
  51279. if (!this._isMainTrack) {
  51280. this._scene.soundTracks.push(this);
  51281. this.id = this._scene.soundTracks.length - 1;
  51282. }
  51283. }
  51284. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51285. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51286. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51287. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51288. if (this._options) {
  51289. if (this._options.volume) {
  51290. this._outputAudioNode.gain.value = this._options.volume;
  51291. }
  51292. if (this._options.mainTrack) {
  51293. this._isMainTrack = this._options.mainTrack;
  51294. }
  51295. }
  51296. this._isInitialized = true;
  51297. }
  51298. };
  51299. SoundTrack.prototype.dispose = function () {
  51300. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51301. if (this._connectedAnalyser) {
  51302. this._connectedAnalyser.stopDebugCanvas();
  51303. }
  51304. while (this.soundCollection.length) {
  51305. this.soundCollection[0].dispose();
  51306. }
  51307. if (this._outputAudioNode) {
  51308. this._outputAudioNode.disconnect();
  51309. }
  51310. this._outputAudioNode = null;
  51311. }
  51312. };
  51313. SoundTrack.prototype.AddSound = function (sound) {
  51314. if (!this._isInitialized) {
  51315. this._initializeSoundTrackAudioGraph();
  51316. }
  51317. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51318. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51319. }
  51320. if (sound.soundTrackId) {
  51321. if (sound.soundTrackId === -1) {
  51322. this._scene.mainSoundTrack.RemoveSound(sound);
  51323. }
  51324. else {
  51325. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51326. }
  51327. }
  51328. this.soundCollection.push(sound);
  51329. sound.soundTrackId = this.id;
  51330. };
  51331. SoundTrack.prototype.RemoveSound = function (sound) {
  51332. var index = this.soundCollection.indexOf(sound);
  51333. if (index !== -1) {
  51334. this.soundCollection.splice(index, 1);
  51335. }
  51336. };
  51337. SoundTrack.prototype.setVolume = function (newVolume) {
  51338. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51339. this._outputAudioNode.gain.value = newVolume;
  51340. }
  51341. };
  51342. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51344. for (var i = 0; i < this.soundCollection.length; i++) {
  51345. this.soundCollection[i].switchPanningModelToHRTF();
  51346. }
  51347. }
  51348. };
  51349. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51350. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51351. for (var i = 0; i < this.soundCollection.length; i++) {
  51352. this.soundCollection[i].switchPanningModelToEqualPower();
  51353. }
  51354. }
  51355. };
  51356. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51357. if (this._connectedAnalyser) {
  51358. this._connectedAnalyser.stopDebugCanvas();
  51359. }
  51360. this._connectedAnalyser = analyser;
  51361. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51362. this._outputAudioNode.disconnect();
  51363. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51364. }
  51365. };
  51366. return SoundTrack;
  51367. }());
  51368. BABYLON.SoundTrack = SoundTrack;
  51369. })(BABYLON || (BABYLON = {}));
  51370. //# sourceMappingURL=babylon.soundtrack.js.map
  51371. var BABYLON;
  51372. (function (BABYLON) {
  51373. var Analyser = /** @class */ (function () {
  51374. function Analyser(scene) {
  51375. this.SMOOTHING = 0.75;
  51376. this.FFT_SIZE = 512;
  51377. this.BARGRAPHAMPLITUDE = 256;
  51378. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51379. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51380. this._scene = scene;
  51381. this._audioEngine = BABYLON.Engine.audioEngine;
  51382. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51383. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51384. this._webAudioAnalyser.minDecibels = -140;
  51385. this._webAudioAnalyser.maxDecibels = 0;
  51386. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51387. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51388. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51389. }
  51390. }
  51391. Analyser.prototype.getFrequencyBinCount = function () {
  51392. if (this._audioEngine.canUseWebAudio) {
  51393. return this._webAudioAnalyser.frequencyBinCount;
  51394. }
  51395. else {
  51396. return 0;
  51397. }
  51398. };
  51399. Analyser.prototype.getByteFrequencyData = function () {
  51400. if (this._audioEngine.canUseWebAudio) {
  51401. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51402. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51403. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51404. }
  51405. return this._byteFreqs;
  51406. };
  51407. Analyser.prototype.getByteTimeDomainData = function () {
  51408. if (this._audioEngine.canUseWebAudio) {
  51409. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51410. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51411. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51412. }
  51413. return this._byteTime;
  51414. };
  51415. Analyser.prototype.getFloatFrequencyData = function () {
  51416. if (this._audioEngine.canUseWebAudio) {
  51417. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51418. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51419. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51420. }
  51421. return this._floatFreqs;
  51422. };
  51423. Analyser.prototype.drawDebugCanvas = function () {
  51424. var _this = this;
  51425. if (this._audioEngine.canUseWebAudio) {
  51426. if (!this._debugCanvas) {
  51427. this._debugCanvas = document.createElement("canvas");
  51428. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51429. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51430. this._debugCanvas.style.position = "absolute";
  51431. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51432. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51433. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51434. document.body.appendChild(this._debugCanvas);
  51435. this._registerFunc = function () {
  51436. _this.drawDebugCanvas();
  51437. };
  51438. this._scene.registerBeforeRender(this._registerFunc);
  51439. }
  51440. if (this._registerFunc && this._debugCanvasContext) {
  51441. var workingArray = this.getByteFrequencyData();
  51442. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51443. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51444. // Draw the frequency domain chart.
  51445. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51446. var value = workingArray[i];
  51447. var percent = value / this.BARGRAPHAMPLITUDE;
  51448. var height = this.DEBUGCANVASSIZE.height * percent;
  51449. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51450. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51451. var hue = i / this.getFrequencyBinCount() * 360;
  51452. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51453. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51454. }
  51455. }
  51456. }
  51457. };
  51458. Analyser.prototype.stopDebugCanvas = function () {
  51459. if (this._debugCanvas) {
  51460. if (this._registerFunc) {
  51461. this._scene.unregisterBeforeRender(this._registerFunc);
  51462. this._registerFunc = null;
  51463. }
  51464. document.body.removeChild(this._debugCanvas);
  51465. this._debugCanvas = null;
  51466. this._debugCanvasContext = null;
  51467. }
  51468. };
  51469. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51470. if (this._audioEngine.canUseWebAudio) {
  51471. inputAudioNode.connect(this._webAudioAnalyser);
  51472. this._webAudioAnalyser.connect(outputAudioNode);
  51473. }
  51474. };
  51475. Analyser.prototype.dispose = function () {
  51476. if (this._audioEngine.canUseWebAudio) {
  51477. this._webAudioAnalyser.disconnect();
  51478. }
  51479. };
  51480. return Analyser;
  51481. }());
  51482. BABYLON.Analyser = Analyser;
  51483. })(BABYLON || (BABYLON = {}));
  51484. //# sourceMappingURL=babylon.analyser.js.map
  51485. var BABYLON;
  51486. (function (BABYLON) {
  51487. var CubeTexture = /** @class */ (function (_super) {
  51488. __extends(CubeTexture, _super);
  51489. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51490. if (extensions === void 0) { extensions = null; }
  51491. if (noMipmap === void 0) { noMipmap = false; }
  51492. if (files === void 0) { files = null; }
  51493. if (onLoad === void 0) { onLoad = null; }
  51494. if (onError === void 0) { onError = null; }
  51495. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51496. if (prefiltered === void 0) { prefiltered = false; }
  51497. if (forcedExtension === void 0) { forcedExtension = null; }
  51498. var _this = _super.call(this, scene) || this;
  51499. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51500. _this.name = rootUrl;
  51501. _this.url = rootUrl;
  51502. _this._noMipmap = noMipmap;
  51503. _this.hasAlpha = false;
  51504. _this._format = format;
  51505. _this._prefiltered = prefiltered;
  51506. _this.isCube = true;
  51507. _this._textureMatrix = BABYLON.Matrix.Identity();
  51508. if (prefiltered) {
  51509. _this.gammaSpace = false;
  51510. }
  51511. if (!rootUrl && !files) {
  51512. return _this;
  51513. }
  51514. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51515. var lastDot = rootUrl.lastIndexOf(".");
  51516. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51517. var isDDS = (extension === ".dds");
  51518. if (!files) {
  51519. if (!isDDS && !extensions) {
  51520. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51521. }
  51522. files = [];
  51523. if (extensions) {
  51524. for (var index = 0; index < extensions.length; index++) {
  51525. files.push(rootUrl + extensions[index]);
  51526. }
  51527. }
  51528. }
  51529. _this._files = files;
  51530. if (!_this._texture) {
  51531. if (!scene.useDelayedTextureLoading) {
  51532. if (prefiltered) {
  51533. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51534. }
  51535. else {
  51536. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51537. }
  51538. }
  51539. else {
  51540. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51541. }
  51542. }
  51543. else if (onLoad) {
  51544. if (_this._texture.isReady) {
  51545. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51546. }
  51547. else {
  51548. _this._texture.onLoadedObservable.add(onLoad);
  51549. }
  51550. }
  51551. return _this;
  51552. }
  51553. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51554. return new CubeTexture("", scene, null, noMipmap, files);
  51555. };
  51556. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51557. if (forcedExtension === void 0) { forcedExtension = null; }
  51558. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51559. };
  51560. // Methods
  51561. CubeTexture.prototype.delayLoad = function () {
  51562. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51563. return;
  51564. }
  51565. var scene = this.getScene();
  51566. if (!scene) {
  51567. return;
  51568. }
  51569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51570. this._texture = this._getFromCache(this.url, this._noMipmap);
  51571. if (!this._texture) {
  51572. if (this._prefiltered) {
  51573. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51574. }
  51575. else {
  51576. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51577. }
  51578. }
  51579. };
  51580. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51581. return this._textureMatrix;
  51582. };
  51583. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51584. this._textureMatrix = value;
  51585. };
  51586. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51587. var texture = BABYLON.SerializationHelper.Parse(function () {
  51588. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51589. }, parsedTexture, scene);
  51590. // Animations
  51591. if (parsedTexture.animations) {
  51592. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51593. var parsedAnimation = parsedTexture.animations[animationIndex];
  51594. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51595. }
  51596. }
  51597. return texture;
  51598. };
  51599. CubeTexture.prototype.clone = function () {
  51600. var _this = this;
  51601. return BABYLON.SerializationHelper.Clone(function () {
  51602. var scene = _this.getScene();
  51603. if (!scene) {
  51604. return _this;
  51605. }
  51606. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51607. }, this);
  51608. };
  51609. return CubeTexture;
  51610. }(BABYLON.BaseTexture));
  51611. BABYLON.CubeTexture = CubeTexture;
  51612. })(BABYLON || (BABYLON = {}));
  51613. //# sourceMappingURL=babylon.cubeTexture.js.map
  51614. var BABYLON;
  51615. (function (BABYLON) {
  51616. var RenderTargetTexture = /** @class */ (function (_super) {
  51617. __extends(RenderTargetTexture, _super);
  51618. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51619. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51620. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51621. if (isCube === void 0) { isCube = false; }
  51622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51623. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51624. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51625. if (isMulti === void 0) { isMulti = false; }
  51626. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51627. _this.isCube = isCube;
  51628. /**
  51629. * Use this list to define the list of mesh you want to render.
  51630. */
  51631. _this.renderList = new Array();
  51632. _this.renderParticles = true;
  51633. _this.renderSprites = false;
  51634. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51635. _this.ignoreCameraViewport = false;
  51636. // Events
  51637. /**
  51638. * An event triggered when the texture is unbind.
  51639. * @type {BABYLON.Observable}
  51640. */
  51641. _this.onBeforeBindObservable = new BABYLON.Observable();
  51642. /**
  51643. * An event triggered when the texture is unbind.
  51644. * @type {BABYLON.Observable}
  51645. */
  51646. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51647. /**
  51648. * An event triggered before rendering the texture
  51649. * @type {BABYLON.Observable}
  51650. */
  51651. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51652. /**
  51653. * An event triggered after rendering the texture
  51654. * @type {BABYLON.Observable}
  51655. */
  51656. _this.onAfterRenderObservable = new BABYLON.Observable();
  51657. /**
  51658. * An event triggered after the texture clear
  51659. * @type {BABYLON.Observable}
  51660. */
  51661. _this.onClearObservable = new BABYLON.Observable();
  51662. _this._currentRefreshId = -1;
  51663. _this._refreshRate = 1;
  51664. _this._samples = 1;
  51665. scene = _this.getScene();
  51666. if (!scene) {
  51667. return _this;
  51668. }
  51669. _this._engine = scene.getEngine();
  51670. _this.name = name;
  51671. _this.isRenderTarget = true;
  51672. _this._initialSizeParameter = size;
  51673. _this._processSizeParameter(size);
  51674. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51675. });
  51676. _this._generateMipMaps = generateMipMaps ? true : false;
  51677. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51678. // Rendering groups
  51679. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51680. if (isMulti) {
  51681. return _this;
  51682. }
  51683. _this._renderTargetOptions = {
  51684. generateMipMaps: generateMipMaps,
  51685. type: type,
  51686. samplingMode: samplingMode,
  51687. generateDepthBuffer: generateDepthBuffer,
  51688. generateStencilBuffer: generateStencilBuffer
  51689. };
  51690. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51691. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51692. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51693. }
  51694. if (isCube) {
  51695. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51696. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51697. _this._textureMatrix = BABYLON.Matrix.Identity();
  51698. }
  51699. else {
  51700. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51701. }
  51702. return _this;
  51703. }
  51704. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51705. get: function () {
  51706. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51707. },
  51708. enumerable: true,
  51709. configurable: true
  51710. });
  51711. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51712. get: function () {
  51713. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51714. },
  51715. enumerable: true,
  51716. configurable: true
  51717. });
  51718. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51719. get: function () {
  51720. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51721. },
  51722. enumerable: true,
  51723. configurable: true
  51724. });
  51725. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51726. set: function (callback) {
  51727. if (this._onAfterUnbindObserver) {
  51728. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51729. }
  51730. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51731. },
  51732. enumerable: true,
  51733. configurable: true
  51734. });
  51735. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51736. set: function (callback) {
  51737. if (this._onBeforeRenderObserver) {
  51738. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51739. }
  51740. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51741. },
  51742. enumerable: true,
  51743. configurable: true
  51744. });
  51745. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51746. set: function (callback) {
  51747. if (this._onAfterRenderObserver) {
  51748. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51749. }
  51750. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51751. },
  51752. enumerable: true,
  51753. configurable: true
  51754. });
  51755. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51756. set: function (callback) {
  51757. if (this._onClearObserver) {
  51758. this.onClearObservable.remove(this._onClearObserver);
  51759. }
  51760. this._onClearObserver = this.onClearObservable.add(callback);
  51761. },
  51762. enumerable: true,
  51763. configurable: true
  51764. });
  51765. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51766. get: function () {
  51767. return this._renderTargetOptions;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. RenderTargetTexture.prototype._onRatioRescale = function () {
  51773. if (this._sizeRatio) {
  51774. this.resize(this._initialSizeParameter);
  51775. }
  51776. };
  51777. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51778. if (size.ratio) {
  51779. this._sizeRatio = size.ratio;
  51780. this._size = {
  51781. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51782. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51783. };
  51784. }
  51785. else {
  51786. this._size = size;
  51787. }
  51788. };
  51789. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51790. get: function () {
  51791. return this._samples;
  51792. },
  51793. set: function (value) {
  51794. if (this._samples === value) {
  51795. return;
  51796. }
  51797. var scene = this.getScene();
  51798. if (!scene) {
  51799. return;
  51800. }
  51801. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51802. },
  51803. enumerable: true,
  51804. configurable: true
  51805. });
  51806. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51807. this._currentRefreshId = -1;
  51808. };
  51809. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51810. get: function () {
  51811. return this._refreshRate;
  51812. },
  51813. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51814. set: function (value) {
  51815. this._refreshRate = value;
  51816. this.resetRefreshCounter();
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51822. if (!this._postProcessManager) {
  51823. var scene = this.getScene();
  51824. if (!scene) {
  51825. return;
  51826. }
  51827. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51828. this._postProcesses = new Array();
  51829. }
  51830. this._postProcesses.push(postProcess);
  51831. this._postProcesses[0].autoClear = false;
  51832. };
  51833. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51834. if (!this._postProcesses) {
  51835. return;
  51836. }
  51837. if (dispose) {
  51838. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51839. var postProcess = _a[_i];
  51840. postProcess.dispose();
  51841. }
  51842. }
  51843. this._postProcesses = [];
  51844. };
  51845. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51846. if (!this._postProcesses) {
  51847. return;
  51848. }
  51849. var index = this._postProcesses.indexOf(postProcess);
  51850. if (index === -1) {
  51851. return;
  51852. }
  51853. this._postProcesses.splice(index, 1);
  51854. if (this._postProcesses.length > 0) {
  51855. this._postProcesses[0].autoClear = false;
  51856. }
  51857. };
  51858. RenderTargetTexture.prototype._shouldRender = function () {
  51859. if (this._currentRefreshId === -1) {
  51860. this._currentRefreshId = 1;
  51861. return true;
  51862. }
  51863. if (this.refreshRate === this._currentRefreshId) {
  51864. this._currentRefreshId = 1;
  51865. return true;
  51866. }
  51867. this._currentRefreshId++;
  51868. return false;
  51869. };
  51870. RenderTargetTexture.prototype.getRenderSize = function () {
  51871. if (this._size.width) {
  51872. return this._size.width;
  51873. }
  51874. return this._size;
  51875. };
  51876. RenderTargetTexture.prototype.getRenderWidth = function () {
  51877. if (this._size.width) {
  51878. return this._size.width;
  51879. }
  51880. return this._size;
  51881. };
  51882. RenderTargetTexture.prototype.getRenderHeight = function () {
  51883. if (this._size.width) {
  51884. return this._size.height;
  51885. }
  51886. return this._size;
  51887. };
  51888. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51889. get: function () {
  51890. return true;
  51891. },
  51892. enumerable: true,
  51893. configurable: true
  51894. });
  51895. RenderTargetTexture.prototype.scale = function (ratio) {
  51896. var newSize = this.getRenderSize() * ratio;
  51897. this.resize(newSize);
  51898. };
  51899. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51900. if (this.isCube) {
  51901. return this._textureMatrix;
  51902. }
  51903. return _super.prototype.getReflectionTextureMatrix.call(this);
  51904. };
  51905. RenderTargetTexture.prototype.resize = function (size) {
  51906. this.releaseInternalTexture();
  51907. var scene = this.getScene();
  51908. if (!scene) {
  51909. return;
  51910. }
  51911. this._processSizeParameter(size);
  51912. if (this.isCube) {
  51913. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51914. }
  51915. else {
  51916. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51917. }
  51918. };
  51919. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51920. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51921. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51922. var scene = this.getScene();
  51923. if (!scene) {
  51924. return;
  51925. }
  51926. var engine = scene.getEngine();
  51927. if (this.useCameraPostProcesses !== undefined) {
  51928. useCameraPostProcess = this.useCameraPostProcesses;
  51929. }
  51930. if (this._waitingRenderList) {
  51931. this.renderList = [];
  51932. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51933. var id = this._waitingRenderList[index];
  51934. var mesh_1 = scene.getMeshByID(id);
  51935. if (mesh_1) {
  51936. this.renderList.push(mesh_1);
  51937. }
  51938. }
  51939. delete this._waitingRenderList;
  51940. }
  51941. // Is predicate defined?
  51942. if (this.renderListPredicate) {
  51943. if (this.renderList) {
  51944. this.renderList.splice(0); // Clear previous renderList
  51945. }
  51946. else {
  51947. this.renderList = [];
  51948. }
  51949. var scene = this.getScene();
  51950. if (!scene) {
  51951. return;
  51952. }
  51953. var sceneMeshes = scene.meshes;
  51954. for (var index = 0; index < sceneMeshes.length; index++) {
  51955. var mesh = sceneMeshes[index];
  51956. if (this.renderListPredicate(mesh)) {
  51957. this.renderList.push(mesh);
  51958. }
  51959. }
  51960. }
  51961. this.onBeforeBindObservable.notifyObservers(this);
  51962. // Set custom projection.
  51963. // Needs to be before binding to prevent changing the aspect ratio.
  51964. var camera;
  51965. if (this.activeCamera) {
  51966. camera = this.activeCamera;
  51967. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51968. if (this.activeCamera !== scene.activeCamera) {
  51969. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51970. }
  51971. }
  51972. else {
  51973. camera = scene.activeCamera;
  51974. if (camera) {
  51975. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51976. }
  51977. }
  51978. // Prepare renderingManager
  51979. this._renderingManager.reset();
  51980. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51981. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51982. var sceneRenderId = scene.getRenderId();
  51983. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51984. var mesh = currentRenderList[meshIndex];
  51985. if (mesh) {
  51986. if (!mesh.isReady()) {
  51987. // Reset _currentRefreshId
  51988. this.resetRefreshCounter();
  51989. continue;
  51990. }
  51991. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51992. var isMasked = void 0;
  51993. if (!this.renderList && camera) {
  51994. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  51995. }
  51996. else {
  51997. isMasked = false;
  51998. }
  51999. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52000. mesh._activate(sceneRenderId);
  52001. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52002. var subMesh = mesh.subMeshes[subIndex];
  52003. scene._activeIndices.addCount(subMesh.indexCount, false);
  52004. this._renderingManager.dispatch(subMesh, mesh);
  52005. }
  52006. }
  52007. }
  52008. }
  52009. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52010. var particleSystem = scene.particleSystems[particleIndex];
  52011. var emitter = particleSystem.emitter;
  52012. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52013. continue;
  52014. }
  52015. if (currentRenderList.indexOf(emitter) >= 0) {
  52016. this._renderingManager.dispatchParticles(particleSystem);
  52017. }
  52018. }
  52019. if (this.isCube) {
  52020. for (var face = 0; face < 6; face++) {
  52021. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52022. scene.incrementRenderId();
  52023. scene.resetCachedMaterial();
  52024. }
  52025. }
  52026. else {
  52027. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52028. }
  52029. this.onAfterUnbindObservable.notifyObservers(this);
  52030. if (scene.activeCamera) {
  52031. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52032. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52033. }
  52034. engine.setViewport(scene.activeCamera.viewport);
  52035. }
  52036. scene.resetCachedMaterial();
  52037. };
  52038. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52039. var minimum = 128;
  52040. var x = renderDimension * scale;
  52041. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52042. // Ensure we don't exceed the render dimension (while staying POT)
  52043. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52044. };
  52045. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52046. var _this = this;
  52047. if (!this._texture) {
  52048. return;
  52049. }
  52050. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52051. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52052. });
  52053. };
  52054. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52055. var scene = this.getScene();
  52056. if (!scene) {
  52057. return;
  52058. }
  52059. var engine = scene.getEngine();
  52060. if (!this._texture) {
  52061. return;
  52062. }
  52063. // Bind
  52064. if (this._postProcessManager) {
  52065. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52066. }
  52067. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52068. if (this._texture) {
  52069. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52070. }
  52071. }
  52072. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52073. // Clear
  52074. if (this.onClearObservable.hasObservers()) {
  52075. this.onClearObservable.notifyObservers(engine);
  52076. }
  52077. else {
  52078. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52079. }
  52080. if (!this._doNotChangeAspectRatio) {
  52081. scene.updateTransformMatrix(true);
  52082. }
  52083. // Render
  52084. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52085. if (this._postProcessManager) {
  52086. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52087. }
  52088. else if (useCameraPostProcess) {
  52089. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52090. }
  52091. if (!this._doNotChangeAspectRatio) {
  52092. scene.updateTransformMatrix(true);
  52093. }
  52094. // Dump ?
  52095. if (dumpForDebug) {
  52096. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52097. }
  52098. // Unbind
  52099. if (!this.isCube || faceIndex === 5) {
  52100. if (this.isCube) {
  52101. if (faceIndex === 5) {
  52102. engine.generateMipMapsForCubemap(this._texture);
  52103. }
  52104. }
  52105. this.unbindFrameBuffer(engine, faceIndex);
  52106. }
  52107. else {
  52108. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52109. }
  52110. };
  52111. /**
  52112. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52113. * This allowed control for front to back rendering or reversly depending of the special needs.
  52114. *
  52115. * @param renderingGroupId The rendering group id corresponding to its index
  52116. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52117. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52118. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52119. */
  52120. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52121. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52122. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52123. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52124. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52125. };
  52126. /**
  52127. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52128. *
  52129. * @param renderingGroupId The rendering group id corresponding to its index
  52130. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52131. */
  52132. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52133. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52134. };
  52135. RenderTargetTexture.prototype.clone = function () {
  52136. var textureSize = this.getSize();
  52137. 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);
  52138. // Base texture
  52139. newTexture.hasAlpha = this.hasAlpha;
  52140. newTexture.level = this.level;
  52141. // RenderTarget Texture
  52142. newTexture.coordinatesMode = this.coordinatesMode;
  52143. if (this.renderList) {
  52144. newTexture.renderList = this.renderList.slice(0);
  52145. }
  52146. return newTexture;
  52147. };
  52148. RenderTargetTexture.prototype.serialize = function () {
  52149. if (!this.name) {
  52150. return null;
  52151. }
  52152. var serializationObject = _super.prototype.serialize.call(this);
  52153. serializationObject.renderTargetSize = this.getRenderSize();
  52154. serializationObject.renderList = [];
  52155. if (this.renderList) {
  52156. for (var index = 0; index < this.renderList.length; index++) {
  52157. serializationObject.renderList.push(this.renderList[index].id);
  52158. }
  52159. }
  52160. return serializationObject;
  52161. };
  52162. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52163. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52164. var objBuffer = this.getInternalTexture();
  52165. var scene = this.getScene();
  52166. if (objBuffer && scene) {
  52167. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52168. }
  52169. };
  52170. RenderTargetTexture.prototype.dispose = function () {
  52171. if (this._postProcessManager) {
  52172. this._postProcessManager.dispose();
  52173. this._postProcessManager = null;
  52174. }
  52175. this.clearPostProcesses(true);
  52176. if (this._resizeObserver) {
  52177. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52178. this._resizeObserver = null;
  52179. }
  52180. this.renderList = null;
  52181. // Remove from custom render targets
  52182. var scene = this.getScene();
  52183. if (!scene) {
  52184. return;
  52185. }
  52186. var index = scene.customRenderTargets.indexOf(this);
  52187. if (index >= 0) {
  52188. scene.customRenderTargets.splice(index, 1);
  52189. }
  52190. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52191. var camera = _a[_i];
  52192. index = camera.customRenderTargets.indexOf(this);
  52193. if (index >= 0) {
  52194. camera.customRenderTargets.splice(index, 1);
  52195. }
  52196. }
  52197. _super.prototype.dispose.call(this);
  52198. };
  52199. RenderTargetTexture.prototype._rebuild = function () {
  52200. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52201. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52202. }
  52203. if (this._postProcessManager) {
  52204. this._postProcessManager._rebuild();
  52205. }
  52206. };
  52207. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52208. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52209. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52210. return RenderTargetTexture;
  52211. }(BABYLON.Texture));
  52212. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52213. })(BABYLON || (BABYLON = {}));
  52214. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52215. var BABYLON;
  52216. (function (BABYLON) {
  52217. ;
  52218. var MultiRenderTarget = /** @class */ (function (_super) {
  52219. __extends(MultiRenderTarget, _super);
  52220. function MultiRenderTarget(name, size, count, scene, options) {
  52221. var _this = this;
  52222. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52223. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52224. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52225. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52226. _this._engine = scene.getEngine();
  52227. if (!_this.isSupported) {
  52228. _this.dispose();
  52229. return;
  52230. }
  52231. var types = [];
  52232. var samplingModes = [];
  52233. for (var i = 0; i < count; i++) {
  52234. if (options && options.types && options.types[i] !== undefined) {
  52235. types.push(options.types[i]);
  52236. }
  52237. else {
  52238. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52239. }
  52240. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52241. samplingModes.push(options.samplingModes[i]);
  52242. }
  52243. else {
  52244. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52245. }
  52246. }
  52247. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52248. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52249. _this._size = size;
  52250. _this._multiRenderTargetOptions = {
  52251. samplingModes: samplingModes,
  52252. generateMipMaps: generateMipMaps,
  52253. generateDepthBuffer: generateDepthBuffer,
  52254. generateStencilBuffer: generateStencilBuffer,
  52255. generateDepthTexture: generateDepthTexture,
  52256. types: types,
  52257. textureCount: count
  52258. };
  52259. _this._createInternalTextures();
  52260. _this._createTextures();
  52261. return _this;
  52262. }
  52263. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52264. get: function () {
  52265. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52266. },
  52267. enumerable: true,
  52268. configurable: true
  52269. });
  52270. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52271. get: function () {
  52272. return this._textures;
  52273. },
  52274. enumerable: true,
  52275. configurable: true
  52276. });
  52277. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52278. get: function () {
  52279. return this._textures[this._textures.length - 1];
  52280. },
  52281. enumerable: true,
  52282. configurable: true
  52283. });
  52284. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52285. set: function (wrap) {
  52286. if (this._textures) {
  52287. for (var i = 0; i < this._textures.length; i++) {
  52288. this._textures[i].wrapU = wrap;
  52289. }
  52290. }
  52291. },
  52292. enumerable: true,
  52293. configurable: true
  52294. });
  52295. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52296. set: function (wrap) {
  52297. if (this._textures) {
  52298. for (var i = 0; i < this._textures.length; i++) {
  52299. this._textures[i].wrapV = wrap;
  52300. }
  52301. }
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. MultiRenderTarget.prototype._rebuild = function () {
  52307. this.releaseInternalTextures();
  52308. this._createInternalTextures();
  52309. for (var i = 0; i < this._internalTextures.length; i++) {
  52310. var texture = this._textures[i];
  52311. texture._texture = this._internalTextures[i];
  52312. }
  52313. // Keeps references to frame buffer and stencil/depth buffer
  52314. this._texture = this._internalTextures[0];
  52315. };
  52316. MultiRenderTarget.prototype._createInternalTextures = function () {
  52317. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52318. };
  52319. MultiRenderTarget.prototype._createTextures = function () {
  52320. this._textures = [];
  52321. for (var i = 0; i < this._internalTextures.length; i++) {
  52322. var texture = new BABYLON.Texture(null, this.getScene());
  52323. texture._texture = this._internalTextures[i];
  52324. this._textures.push(texture);
  52325. }
  52326. // Keeps references to frame buffer and stencil/depth buffer
  52327. this._texture = this._internalTextures[0];
  52328. };
  52329. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52330. get: function () {
  52331. return this._samples;
  52332. },
  52333. set: function (value) {
  52334. if (this._samples === value) {
  52335. return;
  52336. }
  52337. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52338. },
  52339. enumerable: true,
  52340. configurable: true
  52341. });
  52342. MultiRenderTarget.prototype.resize = function (size) {
  52343. this.releaseInternalTextures();
  52344. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52345. this._createInternalTextures();
  52346. };
  52347. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52348. var _this = this;
  52349. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52350. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52351. });
  52352. };
  52353. MultiRenderTarget.prototype.dispose = function () {
  52354. this.releaseInternalTextures();
  52355. _super.prototype.dispose.call(this);
  52356. };
  52357. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52358. if (!this._internalTextures) {
  52359. return;
  52360. }
  52361. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52362. if (this._internalTextures[i] !== undefined) {
  52363. this._internalTextures[i].dispose();
  52364. this._internalTextures.splice(i, 1);
  52365. }
  52366. }
  52367. };
  52368. return MultiRenderTarget;
  52369. }(BABYLON.RenderTargetTexture));
  52370. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52371. })(BABYLON || (BABYLON = {}));
  52372. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52373. var BABYLON;
  52374. (function (BABYLON) {
  52375. var MirrorTexture = /** @class */ (function (_super) {
  52376. __extends(MirrorTexture, _super);
  52377. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52378. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52380. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52381. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52382. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52383. _this._transformMatrix = BABYLON.Matrix.Zero();
  52384. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52385. _this._adaptiveBlurKernel = 0;
  52386. _this._blurKernelX = 0;
  52387. _this._blurKernelY = 0;
  52388. _this._blurRatio = 1.0;
  52389. _this.ignoreCameraViewport = true;
  52390. _this.onBeforeRenderObservable.add(function () {
  52391. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52392. _this._savedViewMatrix = scene.getViewMatrix();
  52393. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52394. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52395. scene.clipPlane = _this.mirrorPlane;
  52396. scene.getEngine().cullBackFaces = false;
  52397. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52398. });
  52399. _this.onAfterRenderObservable.add(function () {
  52400. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52401. scene.getEngine().cullBackFaces = true;
  52402. scene._mirroredCameraPosition = null;
  52403. delete scene.clipPlane;
  52404. });
  52405. return _this;
  52406. }
  52407. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52408. get: function () {
  52409. return this._blurRatio;
  52410. },
  52411. set: function (value) {
  52412. if (this._blurRatio === value) {
  52413. return;
  52414. }
  52415. this._blurRatio = value;
  52416. this._preparePostProcesses();
  52417. },
  52418. enumerable: true,
  52419. configurable: true
  52420. });
  52421. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52422. set: function (value) {
  52423. this._adaptiveBlurKernel = value;
  52424. this._autoComputeBlurKernel();
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52430. set: function (value) {
  52431. this.blurKernelX = value;
  52432. this.blurKernelY = value;
  52433. },
  52434. enumerable: true,
  52435. configurable: true
  52436. });
  52437. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52438. get: function () {
  52439. return this._blurKernelX;
  52440. },
  52441. set: function (value) {
  52442. if (this._blurKernelX === value) {
  52443. return;
  52444. }
  52445. this._blurKernelX = value;
  52446. this._preparePostProcesses();
  52447. },
  52448. enumerable: true,
  52449. configurable: true
  52450. });
  52451. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52452. get: function () {
  52453. return this._blurKernelY;
  52454. },
  52455. set: function (value) {
  52456. if (this._blurKernelY === value) {
  52457. return;
  52458. }
  52459. this._blurKernelY = value;
  52460. this._preparePostProcesses();
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52466. var engine = this.getScene().getEngine();
  52467. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52468. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52469. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52470. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52471. };
  52472. MirrorTexture.prototype._onRatioRescale = function () {
  52473. if (this._sizeRatio) {
  52474. this.resize(this._initialSizeParameter);
  52475. if (!this._adaptiveBlurKernel) {
  52476. this._preparePostProcesses();
  52477. }
  52478. }
  52479. if (this._adaptiveBlurKernel) {
  52480. this._autoComputeBlurKernel();
  52481. }
  52482. };
  52483. MirrorTexture.prototype._preparePostProcesses = function () {
  52484. this.clearPostProcesses(true);
  52485. if (this._blurKernelX && this._blurKernelY) {
  52486. var engine = this.getScene().getEngine();
  52487. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52488. 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);
  52489. this._blurX.autoClear = false;
  52490. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52491. this._blurX.outputTexture = this._texture;
  52492. }
  52493. else {
  52494. this._blurX.alwaysForcePOT = true;
  52495. }
  52496. 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);
  52497. this._blurY.autoClear = false;
  52498. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52499. this.addPostProcess(this._blurX);
  52500. this.addPostProcess(this._blurY);
  52501. }
  52502. else {
  52503. if (this._blurY) {
  52504. this.removePostProcess(this._blurY);
  52505. this._blurY.dispose();
  52506. this._blurY = null;
  52507. }
  52508. if (this._blurX) {
  52509. this.removePostProcess(this._blurX);
  52510. this._blurX.dispose();
  52511. this._blurX = null;
  52512. }
  52513. }
  52514. };
  52515. MirrorTexture.prototype.clone = function () {
  52516. var scene = this.getScene();
  52517. if (!scene) {
  52518. return this;
  52519. }
  52520. var textureSize = this.getSize();
  52521. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52522. // Base texture
  52523. newTexture.hasAlpha = this.hasAlpha;
  52524. newTexture.level = this.level;
  52525. // Mirror Texture
  52526. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52527. if (this.renderList) {
  52528. newTexture.renderList = this.renderList.slice(0);
  52529. }
  52530. return newTexture;
  52531. };
  52532. MirrorTexture.prototype.serialize = function () {
  52533. if (!this.name) {
  52534. return null;
  52535. }
  52536. var serializationObject = _super.prototype.serialize.call(this);
  52537. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52538. return serializationObject;
  52539. };
  52540. return MirrorTexture;
  52541. }(BABYLON.RenderTargetTexture));
  52542. BABYLON.MirrorTexture = MirrorTexture;
  52543. })(BABYLON || (BABYLON = {}));
  52544. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52545. var BABYLON;
  52546. (function (BABYLON) {
  52547. /**
  52548. * Creates a refraction texture used by refraction channel of the standard material.
  52549. * @param name the texture name
  52550. * @param size size of the underlying texture
  52551. * @param scene root scene
  52552. */
  52553. var RefractionTexture = /** @class */ (function (_super) {
  52554. __extends(RefractionTexture, _super);
  52555. function RefractionTexture(name, size, scene, generateMipMaps) {
  52556. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52557. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52558. _this.depth = 2.0;
  52559. _this.onBeforeRenderObservable.add(function () {
  52560. scene.clipPlane = _this.refractionPlane;
  52561. });
  52562. _this.onAfterRenderObservable.add(function () {
  52563. delete scene.clipPlane;
  52564. });
  52565. return _this;
  52566. }
  52567. RefractionTexture.prototype.clone = function () {
  52568. var scene = this.getScene();
  52569. if (!scene) {
  52570. return this;
  52571. }
  52572. var textureSize = this.getSize();
  52573. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52574. // Base texture
  52575. newTexture.hasAlpha = this.hasAlpha;
  52576. newTexture.level = this.level;
  52577. // Refraction Texture
  52578. newTexture.refractionPlane = this.refractionPlane.clone();
  52579. if (this.renderList) {
  52580. newTexture.renderList = this.renderList.slice(0);
  52581. }
  52582. newTexture.depth = this.depth;
  52583. return newTexture;
  52584. };
  52585. RefractionTexture.prototype.serialize = function () {
  52586. if (!this.name) {
  52587. return null;
  52588. }
  52589. var serializationObject = _super.prototype.serialize.call(this);
  52590. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52591. serializationObject.depth = this.depth;
  52592. return serializationObject;
  52593. };
  52594. return RefractionTexture;
  52595. }(BABYLON.RenderTargetTexture));
  52596. BABYLON.RefractionTexture = RefractionTexture;
  52597. })(BABYLON || (BABYLON = {}));
  52598. //# sourceMappingURL=babylon.refractionTexture.js.map
  52599. var BABYLON;
  52600. (function (BABYLON) {
  52601. var DynamicTexture = /** @class */ (function (_super) {
  52602. __extends(DynamicTexture, _super);
  52603. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52604. if (scene === void 0) { scene = null; }
  52605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52606. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52607. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52608. _this.name = name;
  52609. _this._engine = _this.getScene().getEngine();
  52610. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52611. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52612. _this._generateMipMaps = generateMipMaps;
  52613. if (options.getContext) {
  52614. _this._canvas = options;
  52615. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52616. }
  52617. else {
  52618. _this._canvas = document.createElement("canvas");
  52619. if (options.width) {
  52620. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52621. }
  52622. else {
  52623. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52624. }
  52625. }
  52626. var textureSize = _this.getSize();
  52627. _this._canvas.width = textureSize.width;
  52628. _this._canvas.height = textureSize.height;
  52629. _this._context = _this._canvas.getContext("2d");
  52630. return _this;
  52631. }
  52632. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52633. get: function () {
  52634. return true;
  52635. },
  52636. enumerable: true,
  52637. configurable: true
  52638. });
  52639. DynamicTexture.prototype._recreate = function (textureSize) {
  52640. this._canvas.width = textureSize.width;
  52641. this._canvas.height = textureSize.height;
  52642. this.releaseInternalTexture();
  52643. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52644. };
  52645. DynamicTexture.prototype.scale = function (ratio) {
  52646. var textureSize = this.getSize();
  52647. textureSize.width *= ratio;
  52648. textureSize.height *= ratio;
  52649. this._recreate(textureSize);
  52650. };
  52651. DynamicTexture.prototype.scaleTo = function (width, height) {
  52652. var textureSize = this.getSize();
  52653. textureSize.width = width;
  52654. textureSize.height = height;
  52655. this._recreate(textureSize);
  52656. };
  52657. DynamicTexture.prototype.getContext = function () {
  52658. return this._context;
  52659. };
  52660. DynamicTexture.prototype.clear = function () {
  52661. var size = this.getSize();
  52662. this._context.fillRect(0, 0, size.width, size.height);
  52663. };
  52664. DynamicTexture.prototype.update = function (invertY) {
  52665. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52666. };
  52667. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52668. if (update === void 0) { update = true; }
  52669. var size = this.getSize();
  52670. if (clearColor) {
  52671. this._context.fillStyle = clearColor;
  52672. this._context.fillRect(0, 0, size.width, size.height);
  52673. }
  52674. this._context.font = font;
  52675. if (x === null || x === undefined) {
  52676. var textSize = this._context.measureText(text);
  52677. x = (size.width - textSize.width) / 2;
  52678. }
  52679. if (y === null || y === undefined) {
  52680. var fontSize = parseInt((font.replace(/\D/g, '')));
  52681. ;
  52682. y = (size.height / 2) + (fontSize / 3.65);
  52683. }
  52684. this._context.fillStyle = color;
  52685. this._context.fillText(text, x, y);
  52686. if (update) {
  52687. this.update(invertY);
  52688. }
  52689. };
  52690. DynamicTexture.prototype.clone = function () {
  52691. var scene = this.getScene();
  52692. if (!scene) {
  52693. return this;
  52694. }
  52695. var textureSize = this.getSize();
  52696. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52697. // Base texture
  52698. newTexture.hasAlpha = this.hasAlpha;
  52699. newTexture.level = this.level;
  52700. // Dynamic Texture
  52701. newTexture.wrapU = this.wrapU;
  52702. newTexture.wrapV = this.wrapV;
  52703. return newTexture;
  52704. };
  52705. DynamicTexture.prototype._rebuild = function () {
  52706. this.update();
  52707. };
  52708. return DynamicTexture;
  52709. }(BABYLON.Texture));
  52710. BABYLON.DynamicTexture = DynamicTexture;
  52711. })(BABYLON || (BABYLON = {}));
  52712. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52713. var BABYLON;
  52714. (function (BABYLON) {
  52715. var VideoTexture = /** @class */ (function (_super) {
  52716. __extends(VideoTexture, _super);
  52717. /**
  52718. * Creates a video texture.
  52719. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52720. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52721. * @param {BABYLON.Scene} scene is obviously the current scene.
  52722. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52723. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52724. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52725. */
  52726. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52727. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52728. if (invertY === void 0) { invertY = false; }
  52729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52730. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52731. _this._autoLaunch = true;
  52732. var urls = null;
  52733. _this.name = name;
  52734. if (urlsOrVideo instanceof HTMLVideoElement) {
  52735. _this.video = urlsOrVideo;
  52736. }
  52737. else {
  52738. urls = urlsOrVideo;
  52739. _this.video = document.createElement("video");
  52740. _this.video.autoplay = false;
  52741. _this.video.loop = true;
  52742. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52743. }
  52744. _this._engine = _this.getScene().getEngine();
  52745. _this._generateMipMaps = generateMipMaps;
  52746. _this._samplingMode = samplingMode;
  52747. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52748. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52749. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52750. }
  52751. else {
  52752. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52753. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52754. _this._generateMipMaps = false;
  52755. }
  52756. if (urls) {
  52757. _this.video.addEventListener("canplay", function () {
  52758. if (_this._texture === undefined) {
  52759. _this._createTexture();
  52760. }
  52761. });
  52762. urls.forEach(function (url) {
  52763. var source = document.createElement("source");
  52764. source.src = url;
  52765. _this.video.appendChild(source);
  52766. });
  52767. }
  52768. else {
  52769. _this._createTexture();
  52770. }
  52771. _this._lastUpdate = BABYLON.Tools.Now;
  52772. return _this;
  52773. }
  52774. VideoTexture.prototype.__setTextureReady = function () {
  52775. if (this._texture) {
  52776. this._texture.isReady = true;
  52777. }
  52778. };
  52779. VideoTexture.prototype._createTexture = function () {
  52780. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52781. if (this._autoLaunch) {
  52782. this._autoLaunch = false;
  52783. this.video.play();
  52784. }
  52785. this._setTextureReady = this.__setTextureReady.bind(this);
  52786. this.video.addEventListener("playing", this._setTextureReady);
  52787. };
  52788. VideoTexture.prototype._rebuild = function () {
  52789. this.update();
  52790. };
  52791. VideoTexture.prototype.update = function () {
  52792. var now = BABYLON.Tools.Now;
  52793. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52794. return false;
  52795. }
  52796. this._lastUpdate = now;
  52797. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52798. return true;
  52799. };
  52800. VideoTexture.prototype.dispose = function () {
  52801. _super.prototype.dispose.call(this);
  52802. this.video.removeEventListener("playing", this._setTextureReady);
  52803. };
  52804. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52805. var video = document.createElement("video");
  52806. var constraintsDeviceId;
  52807. if (constraints && constraints.deviceId) {
  52808. constraintsDeviceId = {
  52809. exact: constraints.deviceId
  52810. };
  52811. }
  52812. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52813. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52814. if (navigator.getUserMedia) {
  52815. navigator.getUserMedia({
  52816. video: {
  52817. deviceId: constraintsDeviceId,
  52818. width: {
  52819. min: (constraints && constraints.minWidth) || 256,
  52820. max: (constraints && constraints.maxWidth) || 640
  52821. },
  52822. height: {
  52823. min: (constraints && constraints.minHeight) || 256,
  52824. max: (constraints && constraints.maxHeight) || 480
  52825. }
  52826. }
  52827. }, function (stream) {
  52828. if (video.mozSrcObject !== undefined) {
  52829. video.mozSrcObject = stream;
  52830. }
  52831. else {
  52832. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52833. }
  52834. video.play();
  52835. if (onReady) {
  52836. onReady(new VideoTexture("video", video, scene, true, true));
  52837. }
  52838. }, function (e) {
  52839. BABYLON.Tools.Error(e.name);
  52840. });
  52841. }
  52842. };
  52843. return VideoTexture;
  52844. }(BABYLON.Texture));
  52845. BABYLON.VideoTexture = VideoTexture;
  52846. })(BABYLON || (BABYLON = {}));
  52847. //# sourceMappingURL=babylon.videoTexture.js.map
  52848. var BABYLON;
  52849. (function (BABYLON) {
  52850. var RawTexture = /** @class */ (function (_super) {
  52851. __extends(RawTexture, _super);
  52852. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52853. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52854. if (invertY === void 0) { invertY = false; }
  52855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52856. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52857. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52858. _this.format = format;
  52859. _this._engine = scene.getEngine();
  52860. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52861. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52862. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52863. return _this;
  52864. }
  52865. RawTexture.prototype.update = function (data) {
  52866. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52867. };
  52868. // Statics
  52869. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52870. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52871. if (invertY === void 0) { invertY = false; }
  52872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52873. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52874. };
  52875. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52876. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52877. if (invertY === void 0) { invertY = false; }
  52878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52879. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52880. };
  52881. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52882. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52883. if (invertY === void 0) { invertY = false; }
  52884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52885. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52886. };
  52887. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52888. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52889. if (invertY === void 0) { invertY = false; }
  52890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52891. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52892. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52893. };
  52894. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52895. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52896. if (invertY === void 0) { invertY = false; }
  52897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52898. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52899. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52900. };
  52901. return RawTexture;
  52902. }(BABYLON.Texture));
  52903. BABYLON.RawTexture = RawTexture;
  52904. })(BABYLON || (BABYLON = {}));
  52905. //# sourceMappingURL=babylon.rawTexture.js.map
  52906. var BABYLON;
  52907. (function (BABYLON) {
  52908. var PostProcess = /** @class */ (function () {
  52909. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52911. if (defines === void 0) { defines = null; }
  52912. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52913. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52914. if (blockCompilation === void 0) { blockCompilation = false; }
  52915. this.name = name;
  52916. this.width = -1;
  52917. this.height = -1;
  52918. this.autoClear = true;
  52919. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52920. this.animations = new Array();
  52921. /*
  52922. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52923. Can only be used on a single postprocess or on the last one of a chain.
  52924. */
  52925. this.enablePixelPerfectMode = false;
  52926. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52927. this.alwaysForcePOT = false;
  52928. this.samples = 1;
  52929. this.adaptScaleToCurrentViewport = false;
  52930. this._reusable = false;
  52931. this._textures = new BABYLON.SmartArray(2);
  52932. this._currentRenderTextureInd = 0;
  52933. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52934. this._texelSize = BABYLON.Vector2.Zero();
  52935. // Events
  52936. /**
  52937. * An event triggered when the postprocess is activated.
  52938. * @type {BABYLON.Observable}
  52939. */
  52940. this.onActivateObservable = new BABYLON.Observable();
  52941. /**
  52942. * An event triggered when the postprocess changes its size.
  52943. * @type {BABYLON.Observable}
  52944. */
  52945. this.onSizeChangedObservable = new BABYLON.Observable();
  52946. /**
  52947. * An event triggered when the postprocess applies its effect.
  52948. * @type {BABYLON.Observable}
  52949. */
  52950. this.onApplyObservable = new BABYLON.Observable();
  52951. /**
  52952. * An event triggered before rendering the postprocess
  52953. * @type {BABYLON.Observable}
  52954. */
  52955. this.onBeforeRenderObservable = new BABYLON.Observable();
  52956. /**
  52957. * An event triggered after rendering the postprocess
  52958. * @type {BABYLON.Observable}
  52959. */
  52960. this.onAfterRenderObservable = new BABYLON.Observable();
  52961. if (camera != null) {
  52962. this._camera = camera;
  52963. this._scene = camera.getScene();
  52964. camera.attachPostProcess(this);
  52965. this._engine = this._scene.getEngine();
  52966. this._scene.postProcesses.push(this);
  52967. }
  52968. else if (engine) {
  52969. this._engine = engine;
  52970. this._engine.postProcesses.push(this);
  52971. }
  52972. this._options = options;
  52973. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52974. this._reusable = reusable || false;
  52975. this._textureType = textureType;
  52976. this._samplers = samplers || [];
  52977. this._samplers.push("textureSampler");
  52978. this._fragmentUrl = fragmentUrl;
  52979. this._vertexUrl = vertexUrl;
  52980. this._parameters = parameters || [];
  52981. this._parameters.push("scale");
  52982. this._indexParameters = indexParameters;
  52983. if (!blockCompilation) {
  52984. this.updateEffect(defines);
  52985. }
  52986. }
  52987. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52988. set: function (callback) {
  52989. if (this._onActivateObserver) {
  52990. this.onActivateObservable.remove(this._onActivateObserver);
  52991. }
  52992. if (callback) {
  52993. this._onActivateObserver = this.onActivateObservable.add(callback);
  52994. }
  52995. },
  52996. enumerable: true,
  52997. configurable: true
  52998. });
  52999. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53000. set: function (callback) {
  53001. if (this._onSizeChangedObserver) {
  53002. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53003. }
  53004. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53005. },
  53006. enumerable: true,
  53007. configurable: true
  53008. });
  53009. Object.defineProperty(PostProcess.prototype, "onApply", {
  53010. set: function (callback) {
  53011. if (this._onApplyObserver) {
  53012. this.onApplyObservable.remove(this._onApplyObserver);
  53013. }
  53014. this._onApplyObserver = this.onApplyObservable.add(callback);
  53015. },
  53016. enumerable: true,
  53017. configurable: true
  53018. });
  53019. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53020. set: function (callback) {
  53021. if (this._onBeforeRenderObserver) {
  53022. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53023. }
  53024. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53025. },
  53026. enumerable: true,
  53027. configurable: true
  53028. });
  53029. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53030. set: function (callback) {
  53031. if (this._onAfterRenderObserver) {
  53032. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53033. }
  53034. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53035. },
  53036. enumerable: true,
  53037. configurable: true
  53038. });
  53039. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53040. get: function () {
  53041. return this._textures.data[this._currentRenderTextureInd];
  53042. },
  53043. set: function (value) {
  53044. this._forcedOutputTexture = value;
  53045. },
  53046. enumerable: true,
  53047. configurable: true
  53048. });
  53049. PostProcess.prototype.getCamera = function () {
  53050. return this._camera;
  53051. };
  53052. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53053. get: function () {
  53054. if (this._shareOutputWithPostProcess) {
  53055. return this._shareOutputWithPostProcess.texelSize;
  53056. }
  53057. if (this._forcedOutputTexture) {
  53058. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53059. }
  53060. return this._texelSize;
  53061. },
  53062. enumerable: true,
  53063. configurable: true
  53064. });
  53065. PostProcess.prototype.getEngine = function () {
  53066. return this._engine;
  53067. };
  53068. PostProcess.prototype.getEffect = function () {
  53069. return this._effect;
  53070. };
  53071. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53072. this._disposeTextures();
  53073. this._shareOutputWithPostProcess = postProcess;
  53074. return this;
  53075. };
  53076. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53077. if (defines === void 0) { defines = null; }
  53078. if (uniforms === void 0) { uniforms = null; }
  53079. if (samplers === void 0) { samplers = null; }
  53080. 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);
  53081. };
  53082. PostProcess.prototype.isReusable = function () {
  53083. return this._reusable;
  53084. };
  53085. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53086. PostProcess.prototype.markTextureDirty = function () {
  53087. this.width = -1;
  53088. };
  53089. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53090. var _this = this;
  53091. if (sourceTexture === void 0) { sourceTexture = null; }
  53092. camera = camera || this._camera;
  53093. var scene = camera.getScene();
  53094. var engine = scene.getEngine();
  53095. var maxSize = engine.getCaps().maxTextureSize;
  53096. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53097. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53098. var desiredWidth = (this._options.width || requiredWidth);
  53099. var desiredHeight = this._options.height || requiredHeight;
  53100. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53101. if (this.adaptScaleToCurrentViewport) {
  53102. var currentViewport = engine.currentViewport;
  53103. if (currentViewport) {
  53104. desiredWidth *= currentViewport.width;
  53105. desiredHeight *= currentViewport.height;
  53106. }
  53107. }
  53108. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53109. if (!this._options.width) {
  53110. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53111. }
  53112. if (!this._options.height) {
  53113. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53114. }
  53115. }
  53116. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53117. if (this._textures.length > 0) {
  53118. for (var i = 0; i < this._textures.length; i++) {
  53119. this._engine._releaseTexture(this._textures.data[i]);
  53120. }
  53121. this._textures.reset();
  53122. }
  53123. this.width = desiredWidth;
  53124. this.height = desiredHeight;
  53125. var textureSize = { width: this.width, height: this.height };
  53126. var textureOptions = {
  53127. generateMipMaps: false,
  53128. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53129. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53130. samplingMode: this.renderTargetSamplingMode,
  53131. type: this._textureType
  53132. };
  53133. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53134. if (this._reusable) {
  53135. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53136. }
  53137. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53138. this.onSizeChangedObservable.notifyObservers(this);
  53139. }
  53140. this._textures.forEach(function (texture) {
  53141. if (texture.samples !== _this.samples) {
  53142. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53143. }
  53144. });
  53145. }
  53146. var target;
  53147. if (this._shareOutputWithPostProcess) {
  53148. target = this._shareOutputWithPostProcess.outputTexture;
  53149. }
  53150. else if (this._forcedOutputTexture) {
  53151. target = this._forcedOutputTexture;
  53152. this.width = this._forcedOutputTexture.width;
  53153. this.height = this._forcedOutputTexture.height;
  53154. }
  53155. else {
  53156. target = this.outputTexture;
  53157. }
  53158. if (this.enablePixelPerfectMode) {
  53159. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53160. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53161. }
  53162. else {
  53163. this._scaleRatio.copyFromFloats(1, 1);
  53164. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53165. }
  53166. this.onActivateObservable.notifyObservers(camera);
  53167. // Clear
  53168. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53169. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53170. }
  53171. if (this._reusable) {
  53172. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53173. }
  53174. };
  53175. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53176. get: function () {
  53177. return this._effect.isSupported;
  53178. },
  53179. enumerable: true,
  53180. configurable: true
  53181. });
  53182. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53183. get: function () {
  53184. if (this._shareOutputWithPostProcess) {
  53185. return this._shareOutputWithPostProcess.aspectRatio;
  53186. }
  53187. if (this._forcedOutputTexture) {
  53188. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53189. }
  53190. return this.width / this.height;
  53191. },
  53192. enumerable: true,
  53193. configurable: true
  53194. });
  53195. /**
  53196. * Get a value indicating if the post-process is ready to be used
  53197. * @returns true if the post-process is ready (shader is compiled)
  53198. */
  53199. PostProcess.prototype.isReady = function () {
  53200. return this._effect && this._effect.isReady();
  53201. };
  53202. PostProcess.prototype.apply = function () {
  53203. // Check
  53204. if (!this._effect || !this._effect.isReady())
  53205. return null;
  53206. // States
  53207. this._engine.enableEffect(this._effect);
  53208. this._engine.setState(false);
  53209. this._engine.setDepthBuffer(false);
  53210. this._engine.setDepthWrite(false);
  53211. // Alpha
  53212. this._engine.setAlphaMode(this.alphaMode);
  53213. if (this.alphaConstants) {
  53214. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53215. }
  53216. // Texture
  53217. var source;
  53218. if (this._shareOutputWithPostProcess) {
  53219. source = this._shareOutputWithPostProcess.outputTexture;
  53220. }
  53221. else if (this._forcedOutputTexture) {
  53222. source = this._forcedOutputTexture;
  53223. }
  53224. else {
  53225. source = this.outputTexture;
  53226. }
  53227. this._effect._bindTexture("textureSampler", source);
  53228. // Parameters
  53229. this._effect.setVector2("scale", this._scaleRatio);
  53230. this.onApplyObservable.notifyObservers(this._effect);
  53231. return this._effect;
  53232. };
  53233. PostProcess.prototype._disposeTextures = function () {
  53234. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53235. return;
  53236. }
  53237. if (this._textures.length > 0) {
  53238. for (var i = 0; i < this._textures.length; i++) {
  53239. this._engine._releaseTexture(this._textures.data[i]);
  53240. }
  53241. }
  53242. this._textures.dispose();
  53243. };
  53244. PostProcess.prototype.dispose = function (camera) {
  53245. camera = camera || this._camera;
  53246. this._disposeTextures();
  53247. if (this._scene) {
  53248. var index_1 = this._scene.postProcesses.indexOf(this);
  53249. if (index_1 !== -1) {
  53250. this._scene.postProcesses.splice(index_1, 1);
  53251. }
  53252. }
  53253. else {
  53254. var index_2 = this._engine.postProcesses.indexOf(this);
  53255. if (index_2 !== -1) {
  53256. this._engine.postProcesses.splice(index_2, 1);
  53257. }
  53258. }
  53259. if (!camera) {
  53260. return;
  53261. }
  53262. camera.detachPostProcess(this);
  53263. var index = camera._postProcesses.indexOf(this);
  53264. if (index === 0 && camera._postProcesses.length > 0) {
  53265. this._camera._postProcesses[0].markTextureDirty();
  53266. }
  53267. this.onActivateObservable.clear();
  53268. this.onAfterRenderObservable.clear();
  53269. this.onApplyObservable.clear();
  53270. this.onBeforeRenderObservable.clear();
  53271. this.onSizeChangedObservable.clear();
  53272. };
  53273. return PostProcess;
  53274. }());
  53275. BABYLON.PostProcess = PostProcess;
  53276. })(BABYLON || (BABYLON = {}));
  53277. //# sourceMappingURL=babylon.postProcess.js.map
  53278. var BABYLON;
  53279. (function (BABYLON) {
  53280. var PassPostProcess = /** @class */ (function (_super) {
  53281. __extends(PassPostProcess, _super);
  53282. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53283. if (camera === void 0) { camera = null; }
  53284. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53285. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53286. }
  53287. return PassPostProcess;
  53288. }(BABYLON.PostProcess));
  53289. BABYLON.PassPostProcess = PassPostProcess;
  53290. })(BABYLON || (BABYLON = {}));
  53291. //# sourceMappingURL=babylon.passPostProcess.js.map
  53292. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53293. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53294. s = arguments[i];
  53295. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53296. t[p] = s[p];
  53297. }
  53298. return t;
  53299. };
  53300. var BABYLON;
  53301. (function (BABYLON) {
  53302. var ShadowGenerator = /** @class */ (function () {
  53303. /**
  53304. * Creates a ShadowGenerator object.
  53305. * A ShadowGenerator is the required tool to use the shadows.
  53306. * Each light casting shadows needs to use its own ShadowGenerator.
  53307. * Required parameters :
  53308. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53309. * - `light`: the light object generating the shadows.
  53310. * - `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.
  53311. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53312. */
  53313. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53314. // Members
  53315. this._bias = 0.00005;
  53316. this._blurBoxOffset = 1;
  53317. this._blurScale = 2;
  53318. this._blurKernel = 1;
  53319. this._useKernelBlur = false;
  53320. this._filter = ShadowGenerator.FILTER_NONE;
  53321. this._darkness = 0;
  53322. this._transparencyShadow = false;
  53323. /**
  53324. * Controls the extent to which the shadows fade out at the edge of the frustum
  53325. * Used only by directionals and spots
  53326. */
  53327. this.frustumEdgeFalloff = 0;
  53328. this.forceBackFacesOnly = false;
  53329. this._lightDirection = BABYLON.Vector3.Zero();
  53330. this._viewMatrix = BABYLON.Matrix.Zero();
  53331. this._projectionMatrix = BABYLON.Matrix.Zero();
  53332. this._transformMatrix = BABYLON.Matrix.Zero();
  53333. this._currentFaceIndex = 0;
  53334. this._currentFaceIndexCache = 0;
  53335. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53336. this._mapSize = mapSize;
  53337. this._light = light;
  53338. this._scene = light.getScene();
  53339. light._shadowGenerator = this;
  53340. // Texture type fallback from float to int if not supported.
  53341. var caps = this._scene.getEngine().getCaps();
  53342. if (!useFullFloatFirst) {
  53343. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53344. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53345. }
  53346. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53347. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53348. }
  53349. else {
  53350. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53351. }
  53352. }
  53353. else {
  53354. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53355. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53356. }
  53357. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53358. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53359. }
  53360. else {
  53361. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53362. }
  53363. }
  53364. this._initializeGenerator();
  53365. }
  53366. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53367. // Static
  53368. get: function () {
  53369. return ShadowGenerator._FILTER_NONE;
  53370. },
  53371. enumerable: true,
  53372. configurable: true
  53373. });
  53374. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53375. get: function () {
  53376. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53377. },
  53378. enumerable: true,
  53379. configurable: true
  53380. });
  53381. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53382. get: function () {
  53383. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53384. },
  53385. enumerable: true,
  53386. configurable: true
  53387. });
  53388. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53389. get: function () {
  53390. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53391. },
  53392. enumerable: true,
  53393. configurable: true
  53394. });
  53395. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53396. get: function () {
  53397. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53398. },
  53399. enumerable: true,
  53400. configurable: true
  53401. });
  53402. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53403. get: function () {
  53404. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53405. },
  53406. enumerable: true,
  53407. configurable: true
  53408. });
  53409. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53410. get: function () {
  53411. return this._bias;
  53412. },
  53413. set: function (bias) {
  53414. this._bias = bias;
  53415. },
  53416. enumerable: true,
  53417. configurable: true
  53418. });
  53419. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53420. get: function () {
  53421. return this._blurBoxOffset;
  53422. },
  53423. set: function (value) {
  53424. if (this._blurBoxOffset === value) {
  53425. return;
  53426. }
  53427. this._blurBoxOffset = value;
  53428. this._disposeBlurPostProcesses();
  53429. },
  53430. enumerable: true,
  53431. configurable: true
  53432. });
  53433. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53434. get: function () {
  53435. return this._blurScale;
  53436. },
  53437. set: function (value) {
  53438. if (this._blurScale === value) {
  53439. return;
  53440. }
  53441. this._blurScale = value;
  53442. this._disposeBlurPostProcesses();
  53443. },
  53444. enumerable: true,
  53445. configurable: true
  53446. });
  53447. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53448. get: function () {
  53449. return this._blurKernel;
  53450. },
  53451. set: function (value) {
  53452. if (this._blurKernel === value) {
  53453. return;
  53454. }
  53455. this._blurKernel = value;
  53456. this._disposeBlurPostProcesses();
  53457. },
  53458. enumerable: true,
  53459. configurable: true
  53460. });
  53461. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53462. get: function () {
  53463. return this._useKernelBlur;
  53464. },
  53465. set: function (value) {
  53466. if (this._useKernelBlur === value) {
  53467. return;
  53468. }
  53469. this._useKernelBlur = value;
  53470. this._disposeBlurPostProcesses();
  53471. },
  53472. enumerable: true,
  53473. configurable: true
  53474. });
  53475. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53476. get: function () {
  53477. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53478. },
  53479. set: function (value) {
  53480. this._depthScale = value;
  53481. },
  53482. enumerable: true,
  53483. configurable: true
  53484. });
  53485. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53486. get: function () {
  53487. return this._filter;
  53488. },
  53489. set: function (value) {
  53490. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53491. if (this._light.needCube()) {
  53492. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53493. this.useExponentialShadowMap = true;
  53494. return;
  53495. }
  53496. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53497. this.useCloseExponentialShadowMap = true;
  53498. return;
  53499. }
  53500. }
  53501. if (this._filter === value) {
  53502. return;
  53503. }
  53504. this._filter = value;
  53505. this._disposeBlurPostProcesses();
  53506. this._applyFilterValues();
  53507. this._light._markMeshesAsLightDirty();
  53508. },
  53509. enumerable: true,
  53510. configurable: true
  53511. });
  53512. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53513. get: function () {
  53514. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53515. },
  53516. set: function (value) {
  53517. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53518. return;
  53519. }
  53520. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53521. },
  53522. enumerable: true,
  53523. configurable: true
  53524. });
  53525. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53526. get: function () {
  53527. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53528. return this.useExponentialShadowMap;
  53529. },
  53530. set: function (value) {
  53531. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53532. this.useExponentialShadowMap = value;
  53533. },
  53534. enumerable: true,
  53535. configurable: true
  53536. });
  53537. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53538. get: function () {
  53539. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53540. return this.useBlurExponentialShadowMap;
  53541. },
  53542. set: function (value) {
  53543. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53544. this.useBlurExponentialShadowMap = value;
  53545. },
  53546. enumerable: true,
  53547. configurable: true
  53548. });
  53549. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53550. get: function () {
  53551. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53552. },
  53553. set: function (value) {
  53554. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53555. return;
  53556. }
  53557. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53558. },
  53559. enumerable: true,
  53560. configurable: true
  53561. });
  53562. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53563. get: function () {
  53564. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53565. },
  53566. set: function (value) {
  53567. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53568. return;
  53569. }
  53570. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53571. },
  53572. enumerable: true,
  53573. configurable: true
  53574. });
  53575. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53576. get: function () {
  53577. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53578. },
  53579. set: function (value) {
  53580. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53581. return;
  53582. }
  53583. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53584. },
  53585. enumerable: true,
  53586. configurable: true
  53587. });
  53588. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53589. get: function () {
  53590. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53591. },
  53592. set: function (value) {
  53593. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53594. return;
  53595. }
  53596. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53597. },
  53598. enumerable: true,
  53599. configurable: true
  53600. });
  53601. /**
  53602. * Returns the darkness value (float).
  53603. */
  53604. ShadowGenerator.prototype.getDarkness = function () {
  53605. return this._darkness;
  53606. };
  53607. /**
  53608. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53609. * Returns the ShadowGenerator.
  53610. */
  53611. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53612. if (darkness >= 1.0)
  53613. this._darkness = 1.0;
  53614. else if (darkness <= 0.0)
  53615. this._darkness = 0.0;
  53616. else
  53617. this._darkness = darkness;
  53618. return this;
  53619. };
  53620. /**
  53621. * Sets the ability to have transparent shadow (boolean).
  53622. * Returns the ShadowGenerator.
  53623. */
  53624. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53625. this._transparencyShadow = hasShadow;
  53626. return this;
  53627. };
  53628. /**
  53629. * Returns a RenderTargetTexture object : the shadow map texture.
  53630. */
  53631. ShadowGenerator.prototype.getShadowMap = function () {
  53632. return this._shadowMap;
  53633. };
  53634. /**
  53635. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53636. */
  53637. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53638. if (this._shadowMap2) {
  53639. return this._shadowMap2;
  53640. }
  53641. return this._shadowMap;
  53642. };
  53643. /**
  53644. * Helper function to add a mesh and its descendants to the list of shadow casters
  53645. * @param mesh Mesh to add
  53646. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53647. */
  53648. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53649. if (includeDescendants === void 0) { includeDescendants = true; }
  53650. if (!this._shadowMap) {
  53651. return this;
  53652. }
  53653. if (!this._shadowMap.renderList) {
  53654. this._shadowMap.renderList = [];
  53655. }
  53656. this._shadowMap.renderList.push(mesh);
  53657. if (includeDescendants) {
  53658. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53659. }
  53660. return this;
  53661. var _a;
  53662. };
  53663. /**
  53664. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53665. * @param mesh Mesh to remove
  53666. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53667. */
  53668. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53669. if (includeDescendants === void 0) { includeDescendants = true; }
  53670. if (!this._shadowMap || !this._shadowMap.renderList) {
  53671. return this;
  53672. }
  53673. var index = this._shadowMap.renderList.indexOf(mesh);
  53674. if (index !== -1) {
  53675. this._shadowMap.renderList.splice(index, 1);
  53676. }
  53677. if (includeDescendants) {
  53678. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53679. var child = _a[_i];
  53680. this.removeShadowCaster(child);
  53681. }
  53682. }
  53683. return this;
  53684. };
  53685. /**
  53686. * Returns the associated light object.
  53687. */
  53688. ShadowGenerator.prototype.getLight = function () {
  53689. return this._light;
  53690. };
  53691. ShadowGenerator.prototype._initializeGenerator = function () {
  53692. this._light._markMeshesAsLightDirty();
  53693. this._initializeShadowMap();
  53694. };
  53695. ShadowGenerator.prototype._initializeShadowMap = function () {
  53696. var _this = this;
  53697. // Render target
  53698. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53699. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53700. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53701. this._shadowMap.anisotropicFilteringLevel = 1;
  53702. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53703. this._shadowMap.renderParticles = false;
  53704. this._shadowMap.ignoreCameraViewport = true;
  53705. // Record Face Index before render.
  53706. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53707. _this._currentFaceIndex = faceIndex;
  53708. });
  53709. // Custom render function.
  53710. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53711. // Blur if required afer render.
  53712. this._shadowMap.onAfterUnbindObservable.add(function () {
  53713. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53714. return;
  53715. }
  53716. var shadowMap = _this.getShadowMapForRendering();
  53717. if (shadowMap) {
  53718. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53719. }
  53720. });
  53721. // Clear according to the chosen filter.
  53722. this._shadowMap.onClearObservable.add(function (engine) {
  53723. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53724. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53725. }
  53726. else {
  53727. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53728. }
  53729. });
  53730. };
  53731. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53732. var _this = this;
  53733. var engine = this._scene.getEngine();
  53734. var targetSize = this._mapSize / this.blurScale;
  53735. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53736. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53737. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53738. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53739. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53740. }
  53741. if (this.useKernelBlur) {
  53742. 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);
  53743. this._kernelBlurXPostprocess.width = targetSize;
  53744. this._kernelBlurXPostprocess.height = targetSize;
  53745. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53746. effect.setTexture("textureSampler", _this._shadowMap);
  53747. });
  53748. 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);
  53749. this._kernelBlurXPostprocess.autoClear = false;
  53750. this._kernelBlurYPostprocess.autoClear = false;
  53751. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53752. this._kernelBlurXPostprocess.packedFloat = true;
  53753. this._kernelBlurYPostprocess.packedFloat = true;
  53754. }
  53755. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53756. }
  53757. else {
  53758. 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);
  53759. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53760. effect.setFloat2("screenSize", targetSize, targetSize);
  53761. effect.setTexture("textureSampler", _this._shadowMap);
  53762. });
  53763. this._boxBlurPostprocess.autoClear = false;
  53764. this._blurPostProcesses = [this._boxBlurPostprocess];
  53765. }
  53766. };
  53767. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53768. var index;
  53769. var engine = this._scene.getEngine();
  53770. if (depthOnlySubMeshes.length) {
  53771. engine.setColorWrite(false);
  53772. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53773. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53774. }
  53775. engine.setColorWrite(true);
  53776. }
  53777. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53778. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53779. }
  53780. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53781. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53782. }
  53783. if (this._transparencyShadow) {
  53784. for (index = 0; index < transparentSubMeshes.length; index++) {
  53785. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53786. }
  53787. }
  53788. };
  53789. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53790. var _this = this;
  53791. var mesh = subMesh.getRenderingMesh();
  53792. var scene = this._scene;
  53793. var engine = scene.getEngine();
  53794. var material = subMesh.getMaterial();
  53795. if (!material) {
  53796. return;
  53797. }
  53798. // Culling
  53799. engine.setState(material.backFaceCulling);
  53800. // Managing instances
  53801. var batch = mesh._getInstancesRenderList(subMesh._id);
  53802. if (batch.mustReturn) {
  53803. return;
  53804. }
  53805. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53806. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53807. engine.enableEffect(this._effect);
  53808. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53809. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53810. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53811. this._effect.setVector3("lightPosition", this.getLight().position);
  53812. if (scene.activeCamera) {
  53813. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53814. }
  53815. // Alpha test
  53816. if (material && material.needAlphaTesting()) {
  53817. var alphaTexture = material.getAlphaTestTexture();
  53818. if (alphaTexture) {
  53819. this._effect.setTexture("diffuseSampler", alphaTexture);
  53820. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53821. }
  53822. }
  53823. // Bones
  53824. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53825. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53826. }
  53827. if (this.forceBackFacesOnly) {
  53828. engine.setState(true, 0, false, true);
  53829. }
  53830. // Draw
  53831. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53832. if (this.forceBackFacesOnly) {
  53833. engine.setState(true, 0, false, false);
  53834. }
  53835. }
  53836. else {
  53837. // Need to reset refresh rate of the shadowMap
  53838. if (this._shadowMap) {
  53839. this._shadowMap.resetRefreshCounter();
  53840. }
  53841. }
  53842. };
  53843. ShadowGenerator.prototype._applyFilterValues = function () {
  53844. if (!this._shadowMap) {
  53845. return;
  53846. }
  53847. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53848. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53849. }
  53850. else {
  53851. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53852. }
  53853. };
  53854. /**
  53855. * Force shader compilation including textures ready check
  53856. */
  53857. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53858. var _this = this;
  53859. var localOptions = __assign({ useInstances: false }, options);
  53860. var shadowMap = this.getShadowMap();
  53861. if (!shadowMap) {
  53862. if (onCompiled) {
  53863. onCompiled(this);
  53864. }
  53865. return;
  53866. }
  53867. var renderList = shadowMap.renderList;
  53868. if (!renderList) {
  53869. if (onCompiled) {
  53870. onCompiled(this);
  53871. }
  53872. return;
  53873. }
  53874. var subMeshes = new Array();
  53875. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53876. var mesh = renderList_1[_i];
  53877. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53878. }
  53879. if (subMeshes.length === 0) {
  53880. if (onCompiled) {
  53881. onCompiled(this);
  53882. }
  53883. return;
  53884. }
  53885. var currentIndex = 0;
  53886. var checkReady = function () {
  53887. if (!_this._scene || !_this._scene.getEngine()) {
  53888. return;
  53889. }
  53890. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53891. currentIndex++;
  53892. if (currentIndex >= subMeshes.length) {
  53893. if (onCompiled) {
  53894. onCompiled(_this);
  53895. }
  53896. return;
  53897. }
  53898. }
  53899. setTimeout(checkReady, 16);
  53900. };
  53901. checkReady();
  53902. };
  53903. /**
  53904. * Boolean : true when the ShadowGenerator is finally computed.
  53905. */
  53906. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53907. var defines = [];
  53908. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53909. defines.push("#define FLOAT");
  53910. }
  53911. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53912. defines.push("#define ESM");
  53913. }
  53914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53915. var mesh = subMesh.getMesh();
  53916. var material = subMesh.getMaterial();
  53917. // Alpha test
  53918. if (material && material.needAlphaTesting()) {
  53919. var alphaTexture = material.getAlphaTestTexture();
  53920. if (alphaTexture) {
  53921. defines.push("#define ALPHATEST");
  53922. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53923. attribs.push(BABYLON.VertexBuffer.UVKind);
  53924. defines.push("#define UV1");
  53925. }
  53926. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53927. if (alphaTexture.coordinatesIndex === 1) {
  53928. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53929. defines.push("#define UV2");
  53930. }
  53931. }
  53932. }
  53933. }
  53934. // Bones
  53935. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53938. if (mesh.numBoneInfluencers > 4) {
  53939. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53940. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53941. }
  53942. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53943. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53944. }
  53945. else {
  53946. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53947. }
  53948. // Instances
  53949. if (useInstances) {
  53950. defines.push("#define INSTANCES");
  53951. attribs.push("world0");
  53952. attribs.push("world1");
  53953. attribs.push("world2");
  53954. attribs.push("world3");
  53955. }
  53956. // Get correct effect
  53957. var join = defines.join("\n");
  53958. if (this._cachedDefines !== join) {
  53959. this._cachedDefines = join;
  53960. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53961. }
  53962. if (!this._effect.isReady()) {
  53963. return false;
  53964. }
  53965. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53966. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  53967. this._initializeBlurRTTAndPostProcesses();
  53968. }
  53969. }
  53970. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  53971. return false;
  53972. }
  53973. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  53974. return false;
  53975. }
  53976. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  53977. return false;
  53978. }
  53979. return true;
  53980. };
  53981. /**
  53982. * This creates the defines related to the standard BJS materials.
  53983. */
  53984. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53985. var scene = this._scene;
  53986. var light = this._light;
  53987. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53988. return;
  53989. }
  53990. defines["SHADOW" + lightIndex] = true;
  53991. if (this.usePoissonSampling) {
  53992. defines["SHADOWPCF" + lightIndex] = true;
  53993. }
  53994. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53995. defines["SHADOWESM" + lightIndex] = true;
  53996. }
  53997. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53998. defines["SHADOWCLOSEESM" + lightIndex] = true;
  53999. }
  54000. if (light.needCube()) {
  54001. defines["SHADOWCUBE" + lightIndex] = true;
  54002. }
  54003. };
  54004. /**
  54005. * This binds shadow lights related to the standard BJS materials.
  54006. * It implies the unifroms available on the materials are the standard BJS ones.
  54007. */
  54008. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54009. var light = this._light;
  54010. var scene = this._scene;
  54011. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54012. return;
  54013. }
  54014. var camera = scene.activeCamera;
  54015. if (!camera) {
  54016. return;
  54017. }
  54018. var shadowMap = this.getShadowMap();
  54019. if (!shadowMap) {
  54020. return;
  54021. }
  54022. if (!light.needCube()) {
  54023. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54024. }
  54025. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54026. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54027. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54028. };
  54029. // Methods
  54030. /**
  54031. * Returns a Matrix object : the updated transformation matrix.
  54032. */
  54033. ShadowGenerator.prototype.getTransformMatrix = function () {
  54034. var scene = this._scene;
  54035. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54036. return this._transformMatrix;
  54037. }
  54038. this._currentRenderID = scene.getRenderId();
  54039. this._currentFaceIndexCache = this._currentFaceIndex;
  54040. var lightPosition = this._light.position;
  54041. if (this._light.computeTransformedInformation()) {
  54042. lightPosition = this._light.transformedPosition;
  54043. }
  54044. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54045. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54046. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54047. }
  54048. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54049. this._cachedPosition = lightPosition.clone();
  54050. this._cachedDirection = this._lightDirection.clone();
  54051. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54052. var shadowMap = this.getShadowMap();
  54053. if (shadowMap) {
  54054. var renderList = shadowMap.renderList;
  54055. if (renderList) {
  54056. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54057. }
  54058. }
  54059. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54060. }
  54061. return this._transformMatrix;
  54062. };
  54063. ShadowGenerator.prototype.recreateShadowMap = function () {
  54064. var shadowMap = this._shadowMap;
  54065. if (!shadowMap) {
  54066. return;
  54067. }
  54068. // Track render list.
  54069. var renderList = shadowMap.renderList;
  54070. // Clean up existing data.
  54071. this._disposeRTTandPostProcesses();
  54072. // Reinitializes.
  54073. this._initializeGenerator();
  54074. // Reaffect the filter to ensure a correct fallback if necessary.
  54075. this.filter = this.filter;
  54076. // Reaffect the filter.
  54077. this._applyFilterValues();
  54078. // Reaffect Render List.
  54079. this._shadowMap.renderList = renderList;
  54080. };
  54081. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54082. if (this._shadowMap2) {
  54083. this._shadowMap2.dispose();
  54084. this._shadowMap2 = null;
  54085. }
  54086. if (this._boxBlurPostprocess) {
  54087. this._boxBlurPostprocess.dispose();
  54088. this._boxBlurPostprocess = null;
  54089. }
  54090. if (this._kernelBlurXPostprocess) {
  54091. this._kernelBlurXPostprocess.dispose();
  54092. this._kernelBlurXPostprocess = null;
  54093. }
  54094. if (this._kernelBlurYPostprocess) {
  54095. this._kernelBlurYPostprocess.dispose();
  54096. this._kernelBlurYPostprocess = null;
  54097. }
  54098. this._blurPostProcesses = [];
  54099. };
  54100. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54101. if (this._shadowMap) {
  54102. this._shadowMap.dispose();
  54103. this._shadowMap = null;
  54104. }
  54105. this._disposeBlurPostProcesses();
  54106. };
  54107. /**
  54108. * Disposes the ShadowGenerator.
  54109. * Returns nothing.
  54110. */
  54111. ShadowGenerator.prototype.dispose = function () {
  54112. this._disposeRTTandPostProcesses();
  54113. if (this._light) {
  54114. this._light._shadowGenerator = null;
  54115. this._light._markMeshesAsLightDirty();
  54116. }
  54117. };
  54118. /**
  54119. * Serializes the ShadowGenerator and returns a serializationObject.
  54120. */
  54121. ShadowGenerator.prototype.serialize = function () {
  54122. var serializationObject = {};
  54123. var shadowMap = this.getShadowMap();
  54124. if (!shadowMap) {
  54125. return serializationObject;
  54126. }
  54127. serializationObject.lightId = this._light.id;
  54128. serializationObject.mapSize = shadowMap.getRenderSize();
  54129. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54130. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54131. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54132. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54133. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54134. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54135. serializationObject.depthScale = this.depthScale;
  54136. serializationObject.darkness = this.getDarkness();
  54137. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54138. serializationObject.blurKernel = this.blurKernel;
  54139. serializationObject.blurScale = this.blurScale;
  54140. serializationObject.useKernelBlur = this.useKernelBlur;
  54141. serializationObject.transparencyShadow = this._transparencyShadow;
  54142. serializationObject.renderList = [];
  54143. if (shadowMap.renderList) {
  54144. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54145. var mesh = shadowMap.renderList[meshIndex];
  54146. serializationObject.renderList.push(mesh.id);
  54147. }
  54148. }
  54149. return serializationObject;
  54150. };
  54151. /**
  54152. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54153. */
  54154. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54155. //casting to point light, as light is missing the position attr and typescript complains.
  54156. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54157. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54158. var shadowMap = shadowGenerator.getShadowMap();
  54159. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54160. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54161. meshes.forEach(function (mesh) {
  54162. if (!shadowMap) {
  54163. return;
  54164. }
  54165. if (!shadowMap.renderList) {
  54166. shadowMap.renderList = [];
  54167. }
  54168. shadowMap.renderList.push(mesh);
  54169. });
  54170. }
  54171. if (parsedShadowGenerator.usePoissonSampling) {
  54172. shadowGenerator.usePoissonSampling = true;
  54173. }
  54174. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54175. shadowGenerator.useExponentialShadowMap = true;
  54176. }
  54177. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54178. shadowGenerator.useBlurExponentialShadowMap = true;
  54179. }
  54180. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54181. shadowGenerator.useCloseExponentialShadowMap = true;
  54182. }
  54183. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54184. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54185. }
  54186. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54187. shadowGenerator.useExponentialShadowMap = true;
  54188. }
  54189. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54190. shadowGenerator.useBlurExponentialShadowMap = true;
  54191. }
  54192. if (parsedShadowGenerator.depthScale) {
  54193. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54194. }
  54195. if (parsedShadowGenerator.blurScale) {
  54196. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54197. }
  54198. if (parsedShadowGenerator.blurBoxOffset) {
  54199. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54200. }
  54201. if (parsedShadowGenerator.useKernelBlur) {
  54202. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54203. }
  54204. if (parsedShadowGenerator.blurKernel) {
  54205. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54206. }
  54207. if (parsedShadowGenerator.bias !== undefined) {
  54208. shadowGenerator.bias = parsedShadowGenerator.bias;
  54209. }
  54210. if (parsedShadowGenerator.darkness) {
  54211. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54212. }
  54213. if (parsedShadowGenerator.transparencyShadow) {
  54214. shadowGenerator.setTransparencyShadow(true);
  54215. }
  54216. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54217. return shadowGenerator;
  54218. };
  54219. ShadowGenerator._FILTER_NONE = 0;
  54220. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54221. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54222. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54223. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54224. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54225. return ShadowGenerator;
  54226. }());
  54227. BABYLON.ShadowGenerator = ShadowGenerator;
  54228. })(BABYLON || (BABYLON = {}));
  54229. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54230. var BABYLON;
  54231. (function (BABYLON) {
  54232. var DefaultLoadingScreen = /** @class */ (function () {
  54233. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54234. if (_loadingText === void 0) { _loadingText = ""; }
  54235. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54236. var _this = this;
  54237. this._renderingCanvas = _renderingCanvas;
  54238. this._loadingText = _loadingText;
  54239. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54240. // Resize
  54241. this._resizeLoadingUI = function () {
  54242. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54243. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54244. if (!_this._loadingDiv) {
  54245. return;
  54246. }
  54247. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54248. _this._loadingDiv.style.left = canvasRect.left + "px";
  54249. _this._loadingDiv.style.top = canvasRect.top + "px";
  54250. _this._loadingDiv.style.width = canvasRect.width + "px";
  54251. _this._loadingDiv.style.height = canvasRect.height + "px";
  54252. };
  54253. }
  54254. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54255. if (this._loadingDiv) {
  54256. // Do not add a loading screen if there is already one
  54257. return;
  54258. }
  54259. this._loadingDiv = document.createElement("div");
  54260. this._loadingDiv.id = "babylonjsLoadingDiv";
  54261. this._loadingDiv.style.opacity = "0";
  54262. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54263. this._loadingDiv.style.pointerEvents = "none";
  54264. // Loading text
  54265. this._loadingTextDiv = document.createElement("div");
  54266. this._loadingTextDiv.style.position = "absolute";
  54267. this._loadingTextDiv.style.left = "0";
  54268. this._loadingTextDiv.style.top = "50%";
  54269. this._loadingTextDiv.style.marginTop = "80px";
  54270. this._loadingTextDiv.style.width = "100%";
  54271. this._loadingTextDiv.style.height = "20px";
  54272. this._loadingTextDiv.style.fontFamily = "Arial";
  54273. this._loadingTextDiv.style.fontSize = "14px";
  54274. this._loadingTextDiv.style.color = "white";
  54275. this._loadingTextDiv.style.textAlign = "center";
  54276. this._loadingTextDiv.innerHTML = "Loading";
  54277. this._loadingDiv.appendChild(this._loadingTextDiv);
  54278. //set the predefined text
  54279. this._loadingTextDiv.innerHTML = this._loadingText;
  54280. // Generating keyframes
  54281. var style = document.createElement('style');
  54282. style.type = 'text/css';
  54283. 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 }";
  54284. style.innerHTML = keyFrames;
  54285. document.getElementsByTagName('head')[0].appendChild(style);
  54286. // Loading img
  54287. var imgBack = new Image();
  54288. 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";
  54289. imgBack.style.position = "absolute";
  54290. imgBack.style.left = "50%";
  54291. imgBack.style.top = "50%";
  54292. imgBack.style.marginLeft = "-60px";
  54293. imgBack.style.marginTop = "-60px";
  54294. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54295. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54296. imgBack.style.transformOrigin = "50% 50%";
  54297. imgBack.style.webkitTransformOrigin = "50% 50%";
  54298. this._loadingDiv.appendChild(imgBack);
  54299. this._resizeLoadingUI();
  54300. window.addEventListener("resize", this._resizeLoadingUI);
  54301. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54302. document.body.appendChild(this._loadingDiv);
  54303. this._loadingDiv.style.opacity = "1";
  54304. };
  54305. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54306. var _this = this;
  54307. if (!this._loadingDiv) {
  54308. return;
  54309. }
  54310. var onTransitionEnd = function () {
  54311. if (!_this._loadingDiv) {
  54312. return;
  54313. }
  54314. document.body.removeChild(_this._loadingDiv);
  54315. window.removeEventListener("resize", _this._resizeLoadingUI);
  54316. _this._loadingDiv = null;
  54317. };
  54318. this._loadingDiv.style.opacity = "0";
  54319. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54320. };
  54321. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54322. set: function (text) {
  54323. this._loadingText = text;
  54324. if (this._loadingTextDiv) {
  54325. this._loadingTextDiv.innerHTML = this._loadingText;
  54326. }
  54327. },
  54328. enumerable: true,
  54329. configurable: true
  54330. });
  54331. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54332. get: function () {
  54333. return this._loadingDivBackgroundColor;
  54334. },
  54335. set: function (color) {
  54336. this._loadingDivBackgroundColor = color;
  54337. if (!this._loadingDiv) {
  54338. return;
  54339. }
  54340. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54341. },
  54342. enumerable: true,
  54343. configurable: true
  54344. });
  54345. return DefaultLoadingScreen;
  54346. }());
  54347. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54348. })(BABYLON || (BABYLON = {}));
  54349. //# sourceMappingURL=babylon.loadingScreen.js.map
  54350. var BABYLON;
  54351. (function (BABYLON) {
  54352. var SceneLoaderProgressEvent = /** @class */ (function () {
  54353. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54354. this.lengthComputable = lengthComputable;
  54355. this.loaded = loaded;
  54356. this.total = total;
  54357. }
  54358. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54359. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54360. };
  54361. return SceneLoaderProgressEvent;
  54362. }());
  54363. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54364. var SceneLoader = /** @class */ (function () {
  54365. function SceneLoader() {
  54366. }
  54367. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54368. get: function () {
  54369. return 0;
  54370. },
  54371. enumerable: true,
  54372. configurable: true
  54373. });
  54374. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54375. get: function () {
  54376. return 1;
  54377. },
  54378. enumerable: true,
  54379. configurable: true
  54380. });
  54381. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54382. get: function () {
  54383. return 2;
  54384. },
  54385. enumerable: true,
  54386. configurable: true
  54387. });
  54388. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54389. get: function () {
  54390. return 3;
  54391. },
  54392. enumerable: true,
  54393. configurable: true
  54394. });
  54395. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54396. get: function () {
  54397. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54398. },
  54399. set: function (value) {
  54400. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54401. },
  54402. enumerable: true,
  54403. configurable: true
  54404. });
  54405. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54406. get: function () {
  54407. return SceneLoader._ShowLoadingScreen;
  54408. },
  54409. set: function (value) {
  54410. SceneLoader._ShowLoadingScreen = value;
  54411. },
  54412. enumerable: true,
  54413. configurable: true
  54414. });
  54415. Object.defineProperty(SceneLoader, "loggingLevel", {
  54416. get: function () {
  54417. return SceneLoader._loggingLevel;
  54418. },
  54419. set: function (value) {
  54420. SceneLoader._loggingLevel = value;
  54421. },
  54422. enumerable: true,
  54423. configurable: true
  54424. });
  54425. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54426. get: function () {
  54427. return SceneLoader._CleanBoneMatrixWeights;
  54428. },
  54429. set: function (value) {
  54430. SceneLoader._CleanBoneMatrixWeights = value;
  54431. },
  54432. enumerable: true,
  54433. configurable: true
  54434. });
  54435. SceneLoader._getDefaultPlugin = function () {
  54436. return SceneLoader._registeredPlugins[".babylon"];
  54437. };
  54438. SceneLoader._getPluginForExtension = function (extension) {
  54439. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54440. if (registeredPlugin) {
  54441. return registeredPlugin;
  54442. }
  54443. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54444. return SceneLoader._getDefaultPlugin();
  54445. };
  54446. SceneLoader._getPluginForDirectLoad = function (data) {
  54447. for (var extension in SceneLoader._registeredPlugins) {
  54448. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54449. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54450. return SceneLoader._registeredPlugins[extension];
  54451. }
  54452. }
  54453. return SceneLoader._getDefaultPlugin();
  54454. };
  54455. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54456. if (sceneFilename.name) {
  54457. sceneFilename = sceneFilename.name;
  54458. }
  54459. var queryStringPosition = sceneFilename.indexOf("?");
  54460. if (queryStringPosition !== -1) {
  54461. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54462. }
  54463. var dotPosition = sceneFilename.lastIndexOf(".");
  54464. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54465. return SceneLoader._getPluginForExtension(extension);
  54466. };
  54467. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54468. SceneLoader._getDirectLoad = function (sceneFilename) {
  54469. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54470. return sceneFilename.substr(5);
  54471. }
  54472. return null;
  54473. };
  54474. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54475. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54476. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54477. var plugin;
  54478. if (registeredPlugin.plugin.createPlugin) {
  54479. plugin = registeredPlugin.plugin.createPlugin();
  54480. }
  54481. else {
  54482. plugin = registeredPlugin.plugin;
  54483. }
  54484. var useArrayBuffer = registeredPlugin.isBinary;
  54485. var database;
  54486. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54487. var dataCallback = function (data, responseURL) {
  54488. if (scene.isDisposed) {
  54489. onError("Scene has been disposed");
  54490. return;
  54491. }
  54492. scene.database = database;
  54493. onSuccess(plugin, data, responseURL);
  54494. };
  54495. var request = null;
  54496. var pluginDisposed = false;
  54497. var onDisposeObservable = plugin.onDisposeObservable;
  54498. if (onDisposeObservable) {
  54499. onDisposeObservable.add(function () {
  54500. pluginDisposed = true;
  54501. if (request) {
  54502. request.abort();
  54503. request = null;
  54504. }
  54505. onDispose();
  54506. });
  54507. }
  54508. var manifestChecked = function () {
  54509. if (pluginDisposed) {
  54510. return;
  54511. }
  54512. var url = rootUrl + sceneFilename;
  54513. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54514. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54515. } : undefined, database, useArrayBuffer, function (request, exception) {
  54516. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54517. });
  54518. };
  54519. if (directLoad) {
  54520. dataCallback(directLoad);
  54521. return plugin;
  54522. }
  54523. if (rootUrl.indexOf("file:") === -1) {
  54524. if (scene.getEngine().enableOfflineSupport) {
  54525. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54526. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54527. }
  54528. else {
  54529. manifestChecked();
  54530. }
  54531. }
  54532. else {
  54533. var fileOrString = sceneFilename;
  54534. if (fileOrString.name) {
  54535. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54536. }
  54537. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54538. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54539. }
  54540. else {
  54541. onError("Unable to find file named " + sceneFilename);
  54542. }
  54543. }
  54544. return plugin;
  54545. };
  54546. // Public functions
  54547. SceneLoader.GetPluginForExtension = function (extension) {
  54548. return SceneLoader._getPluginForExtension(extension).plugin;
  54549. };
  54550. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54551. return !!SceneLoader._registeredPlugins[extension];
  54552. };
  54553. SceneLoader.RegisterPlugin = function (plugin) {
  54554. if (typeof plugin.extensions === "string") {
  54555. var extension = plugin.extensions;
  54556. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54557. plugin: plugin,
  54558. isBinary: false
  54559. };
  54560. }
  54561. else {
  54562. var extensions = plugin.extensions;
  54563. Object.keys(extensions).forEach(function (extension) {
  54564. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54565. plugin: plugin,
  54566. isBinary: extensions[extension].isBinary
  54567. };
  54568. });
  54569. }
  54570. };
  54571. /**
  54572. * Import meshes into a scene
  54573. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54574. * @param rootUrl a string that defines the root url for scene and resources
  54575. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54576. * @param scene the instance of BABYLON.Scene to append to
  54577. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54578. * @param onProgress a callback with a progress event for each file being loaded
  54579. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54580. */
  54581. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54582. if (onSuccess === void 0) { onSuccess = null; }
  54583. if (onProgress === void 0) { onProgress = null; }
  54584. if (onError === void 0) { onError = null; }
  54585. if (pluginExtension === void 0) { pluginExtension = null; }
  54586. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54587. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54588. return null;
  54589. }
  54590. var loadingToken = {};
  54591. scene._addPendingData(loadingToken);
  54592. var disposeHandler = function () {
  54593. scene._removePendingData(loadingToken);
  54594. };
  54595. var errorHandler = function (message, exception) {
  54596. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54597. if (onError) {
  54598. onError(scene, errorMessage, exception);
  54599. }
  54600. else {
  54601. BABYLON.Tools.Error(errorMessage);
  54602. // should the exception be thrown?
  54603. }
  54604. disposeHandler();
  54605. };
  54606. var progressHandler = onProgress ? function (event) {
  54607. try {
  54608. onProgress(event);
  54609. }
  54610. catch (e) {
  54611. errorHandler("Error in onProgress callback", e);
  54612. }
  54613. } : undefined;
  54614. var successHandler = function (meshes, particleSystems, skeletons) {
  54615. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54616. if (onSuccess) {
  54617. try {
  54618. onSuccess(meshes, particleSystems, skeletons);
  54619. }
  54620. catch (e) {
  54621. errorHandler("Error in onSuccess callback", e);
  54622. }
  54623. }
  54624. scene._removePendingData(loadingToken);
  54625. };
  54626. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54627. if (plugin.rewriteRootURL) {
  54628. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54629. }
  54630. if (plugin.importMesh) {
  54631. var syncedPlugin = plugin;
  54632. var meshes = new Array();
  54633. var particleSystems = new Array();
  54634. var skeletons = new Array();
  54635. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54636. return;
  54637. }
  54638. scene.loadingPluginName = plugin.name;
  54639. successHandler(meshes, particleSystems, skeletons);
  54640. }
  54641. else {
  54642. var asyncedPlugin = plugin;
  54643. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54644. scene.loadingPluginName = plugin.name;
  54645. successHandler(meshes, particleSystems, skeletons);
  54646. }, progressHandler, errorHandler);
  54647. }
  54648. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54649. };
  54650. /**
  54651. * Load a scene
  54652. * @param rootUrl a string that defines the root url for scene and resources
  54653. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54654. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54655. * @param onSuccess a callback with the scene when import succeeds
  54656. * @param onProgress a callback with a progress event for each file being loaded
  54657. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54658. */
  54659. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54660. if (onSuccess === void 0) { onSuccess = null; }
  54661. if (onProgress === void 0) { onProgress = null; }
  54662. if (onError === void 0) { onError = null; }
  54663. if (pluginExtension === void 0) { pluginExtension = null; }
  54664. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54665. };
  54666. /**
  54667. * Append a scene
  54668. * @param rootUrl a string that defines the root url for scene and resources
  54669. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54670. * @param scene is the instance of BABYLON.Scene to append to
  54671. * @param onSuccess a callback with the scene when import succeeds
  54672. * @param onProgress a callback with a progress event for each file being loaded
  54673. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54674. */
  54675. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54676. if (onSuccess === void 0) { onSuccess = null; }
  54677. if (onProgress === void 0) { onProgress = null; }
  54678. if (onError === void 0) { onError = null; }
  54679. if (pluginExtension === void 0) { pluginExtension = null; }
  54680. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54681. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54682. return null;
  54683. }
  54684. if (SceneLoader.ShowLoadingScreen) {
  54685. scene.getEngine().displayLoadingUI();
  54686. }
  54687. var loadingToken = {};
  54688. scene._addPendingData(loadingToken);
  54689. var disposeHandler = function () {
  54690. scene._removePendingData(loadingToken);
  54691. scene.getEngine().hideLoadingUI();
  54692. };
  54693. var errorHandler = function (message, exception) {
  54694. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54695. if (onError) {
  54696. onError(scene, errorMessage, exception);
  54697. }
  54698. else {
  54699. BABYLON.Tools.Error(errorMessage);
  54700. // should the exception be thrown?
  54701. }
  54702. disposeHandler();
  54703. };
  54704. var progressHandler = onProgress ? function (event) {
  54705. try {
  54706. onProgress(event);
  54707. }
  54708. catch (e) {
  54709. errorHandler("Error in onProgress callback", e);
  54710. }
  54711. } : undefined;
  54712. var successHandler = function () {
  54713. if (onSuccess) {
  54714. try {
  54715. onSuccess(scene);
  54716. }
  54717. catch (e) {
  54718. errorHandler("Error in onSuccess callback", e);
  54719. }
  54720. }
  54721. scene._removePendingData(loadingToken);
  54722. };
  54723. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54724. if (plugin.load) {
  54725. var syncedPlugin = plugin;
  54726. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54727. return;
  54728. }
  54729. scene.loadingPluginName = plugin.name;
  54730. successHandler();
  54731. }
  54732. else {
  54733. var asyncedPlugin = plugin;
  54734. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54735. scene.loadingPluginName = plugin.name;
  54736. successHandler();
  54737. }, progressHandler, errorHandler);
  54738. }
  54739. if (SceneLoader.ShowLoadingScreen) {
  54740. scene.executeWhenReady(function () {
  54741. scene.getEngine().hideLoadingUI();
  54742. });
  54743. }
  54744. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54745. };
  54746. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54747. if (onSuccess === void 0) { onSuccess = null; }
  54748. if (onProgress === void 0) { onProgress = null; }
  54749. if (onError === void 0) { onError = null; }
  54750. if (pluginExtension === void 0) { pluginExtension = null; }
  54751. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54752. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54753. return null;
  54754. }
  54755. var loadingToken = {};
  54756. scene._addPendingData(loadingToken);
  54757. var disposeHandler = function () {
  54758. scene._removePendingData(loadingToken);
  54759. };
  54760. var errorHandler = function (message, exception) {
  54761. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54762. if (onError) {
  54763. onError(scene, errorMessage, exception);
  54764. }
  54765. else {
  54766. BABYLON.Tools.Error(errorMessage);
  54767. // should the exception be thrown?
  54768. }
  54769. disposeHandler();
  54770. };
  54771. var progressHandler = onProgress ? function (event) {
  54772. try {
  54773. onProgress(event);
  54774. }
  54775. catch (e) {
  54776. errorHandler("Error in onProgress callback", e);
  54777. }
  54778. } : undefined;
  54779. var successHandler = function (assets) {
  54780. if (onSuccess) {
  54781. try {
  54782. onSuccess(assets);
  54783. }
  54784. catch (e) {
  54785. errorHandler("Error in onSuccess callback", e);
  54786. }
  54787. }
  54788. scene._removePendingData(loadingToken);
  54789. };
  54790. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54791. if (plugin.loadAssets) {
  54792. var syncedPlugin = plugin;
  54793. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54794. if (!assetContainer) {
  54795. return;
  54796. }
  54797. scene.loadingPluginName = plugin.name;
  54798. successHandler(assetContainer);
  54799. }
  54800. else if (plugin.loadAssetsAsync) {
  54801. var asyncedPlugin = plugin;
  54802. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  54803. if (assetContainer) {
  54804. scene.loadingPluginName = plugin.name;
  54805. successHandler(assetContainer);
  54806. }
  54807. }, progressHandler, errorHandler);
  54808. }
  54809. else {
  54810. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  54811. }
  54812. if (SceneLoader.ShowLoadingScreen) {
  54813. scene.executeWhenReady(function () {
  54814. scene.getEngine().hideLoadingUI();
  54815. });
  54816. }
  54817. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54818. };
  54819. // Flags
  54820. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54821. SceneLoader._ShowLoadingScreen = true;
  54822. SceneLoader._CleanBoneMatrixWeights = false;
  54823. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54824. // Members
  54825. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54826. SceneLoader._registeredPlugins = {};
  54827. return SceneLoader;
  54828. }());
  54829. BABYLON.SceneLoader = SceneLoader;
  54830. ;
  54831. })(BABYLON || (BABYLON = {}));
  54832. //# sourceMappingURL=babylon.sceneLoader.js.map
  54833. var BABYLON;
  54834. (function (BABYLON) {
  54835. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54836. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54837. var parsedMaterial = parsedData.materials[index];
  54838. if (parsedMaterial.id === id) {
  54839. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54840. }
  54841. }
  54842. return null;
  54843. };
  54844. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54845. for (var i in names) {
  54846. if (mesh.name === names[i]) {
  54847. hierarchyIds.push(mesh.id);
  54848. return true;
  54849. }
  54850. }
  54851. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54852. hierarchyIds.push(mesh.id);
  54853. return true;
  54854. }
  54855. return false;
  54856. };
  54857. var logOperation = function (operation, producer) {
  54858. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54859. };
  54860. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  54861. if (addToScene === void 0) { addToScene = false; }
  54862. var container = new BABYLON.AssetContainer(scene);
  54863. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54864. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54865. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54866. // and avoid problems with multiple concurrent .babylon loads.
  54867. var log = "importScene has failed JSON parse";
  54868. try {
  54869. var parsedData = JSON.parse(data);
  54870. log = "";
  54871. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54872. var index;
  54873. var cache;
  54874. // Lights
  54875. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54876. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54877. var parsedLight = parsedData.lights[index];
  54878. var light = BABYLON.Light.Parse(parsedLight, scene);
  54879. if (light) {
  54880. container.lights.push(light);
  54881. log += (index === 0 ? "\n\tLights:" : "");
  54882. log += "\n\t\t" + light.toString(fullDetails);
  54883. }
  54884. }
  54885. }
  54886. // Animations
  54887. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54888. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54889. var parsedAnimation = parsedData.animations[index];
  54890. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54891. scene.animations.push(animation);
  54892. container.animations.push(animation);
  54893. log += (index === 0 ? "\n\tAnimations:" : "");
  54894. log += "\n\t\t" + animation.toString(fullDetails);
  54895. }
  54896. }
  54897. // Materials
  54898. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54899. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54900. var parsedMaterial = parsedData.materials[index];
  54901. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54902. container.materials.push(mat);
  54903. log += (index === 0 ? "\n\tMaterials:" : "");
  54904. log += "\n\t\t" + mat.toString(fullDetails);
  54905. }
  54906. }
  54907. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54908. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54909. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54910. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54911. container.multiMaterials.push(mmat);
  54912. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54913. log += "\n\t\t" + mmat.toString(fullDetails);
  54914. }
  54915. }
  54916. // Morph targets
  54917. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54918. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54919. var managerData = _a[_i];
  54920. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  54921. }
  54922. }
  54923. // Skeletons
  54924. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54925. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54926. var parsedSkeleton = parsedData.skeletons[index];
  54927. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54928. container.skeletons.push(skeleton);
  54929. log += (index === 0 ? "\n\tSkeletons:" : "");
  54930. log += "\n\t\t" + skeleton.toString(fullDetails);
  54931. }
  54932. }
  54933. // Geometries
  54934. var geometries = parsedData.geometries;
  54935. if (geometries !== undefined && geometries !== null) {
  54936. var addedGeometry = new Array();
  54937. // Boxes
  54938. var boxes = geometries.boxes;
  54939. if (boxes !== undefined && boxes !== null) {
  54940. for (index = 0, cache = boxes.length; index < cache; index++) {
  54941. var parsedBox = boxes[index];
  54942. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  54943. }
  54944. }
  54945. // Spheres
  54946. var spheres = geometries.spheres;
  54947. if (spheres !== undefined && spheres !== null) {
  54948. for (index = 0, cache = spheres.length; index < cache; index++) {
  54949. var parsedSphere = spheres[index];
  54950. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  54951. }
  54952. }
  54953. // Cylinders
  54954. var cylinders = geometries.cylinders;
  54955. if (cylinders !== undefined && cylinders !== null) {
  54956. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54957. var parsedCylinder = cylinders[index];
  54958. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  54959. }
  54960. }
  54961. // Toruses
  54962. var toruses = geometries.toruses;
  54963. if (toruses !== undefined && toruses !== null) {
  54964. for (index = 0, cache = toruses.length; index < cache; index++) {
  54965. var parsedTorus = toruses[index];
  54966. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  54967. }
  54968. }
  54969. // Grounds
  54970. var grounds = geometries.grounds;
  54971. if (grounds !== undefined && grounds !== null) {
  54972. for (index = 0, cache = grounds.length; index < cache; index++) {
  54973. var parsedGround = grounds[index];
  54974. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  54975. }
  54976. }
  54977. // Planes
  54978. var planes = geometries.planes;
  54979. if (planes !== undefined && planes !== null) {
  54980. for (index = 0, cache = planes.length; index < cache; index++) {
  54981. var parsedPlane = planes[index];
  54982. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  54983. }
  54984. }
  54985. // TorusKnots
  54986. var torusKnots = geometries.torusKnots;
  54987. if (torusKnots !== undefined && torusKnots !== null) {
  54988. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54989. var parsedTorusKnot = torusKnots[index];
  54990. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  54991. }
  54992. }
  54993. // VertexData
  54994. var vertexData = geometries.vertexData;
  54995. if (vertexData !== undefined && vertexData !== null) {
  54996. for (index = 0, cache = vertexData.length; index < cache; index++) {
  54997. var parsedVertexData = vertexData[index];
  54998. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  54999. }
  55000. }
  55001. addedGeometry.forEach(function (g) {
  55002. if (g) {
  55003. container.geometries.push(g);
  55004. }
  55005. });
  55006. }
  55007. // Transform nodes
  55008. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55009. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55010. var parsedTransformNode = parsedData.transformNodes[index];
  55011. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55012. container.transformNodes.push(node);
  55013. }
  55014. }
  55015. // Meshes
  55016. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55017. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55018. var parsedMesh = parsedData.meshes[index];
  55019. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55020. container.meshes.push(mesh);
  55021. log += (index === 0 ? "\n\tMeshes:" : "");
  55022. log += "\n\t\t" + mesh.toString(fullDetails);
  55023. }
  55024. }
  55025. // Cameras
  55026. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55027. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55028. var parsedCamera = parsedData.cameras[index];
  55029. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55030. container.cameras.push(camera);
  55031. log += (index === 0 ? "\n\tCameras:" : "");
  55032. log += "\n\t\t" + camera.toString(fullDetails);
  55033. }
  55034. }
  55035. // Browsing all the graph to connect the dots
  55036. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55037. var camera = scene.cameras[index];
  55038. if (camera._waitingParentId) {
  55039. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55040. camera._waitingParentId = null;
  55041. }
  55042. }
  55043. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55044. var light_1 = scene.lights[index];
  55045. if (light_1 && light_1._waitingParentId) {
  55046. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55047. light_1._waitingParentId = null;
  55048. }
  55049. }
  55050. // Sounds
  55051. // TODO: add sound
  55052. var loadedSounds = [];
  55053. var loadedSound;
  55054. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55055. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55056. var parsedSound = parsedData.sounds[index];
  55057. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55058. if (!parsedSound.url)
  55059. parsedSound.url = parsedSound.name;
  55060. if (!loadedSounds[parsedSound.url]) {
  55061. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55062. loadedSounds[parsedSound.url] = loadedSound;
  55063. container.sounds.push(loadedSound);
  55064. }
  55065. else {
  55066. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55067. }
  55068. }
  55069. else {
  55070. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55071. }
  55072. }
  55073. }
  55074. loadedSounds = [];
  55075. // Connect parents & children and parse actions
  55076. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55077. var transformNode = scene.transformNodes[index];
  55078. if (transformNode._waitingParentId) {
  55079. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55080. transformNode._waitingParentId = null;
  55081. }
  55082. }
  55083. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55084. var mesh = scene.meshes[index];
  55085. if (mesh._waitingParentId) {
  55086. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55087. mesh._waitingParentId = null;
  55088. }
  55089. if (mesh._waitingActions) {
  55090. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55091. mesh._waitingActions = null;
  55092. }
  55093. }
  55094. // freeze world matrix application
  55095. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55096. var currentMesh = scene.meshes[index];
  55097. if (currentMesh._waitingFreezeWorldMatrix) {
  55098. currentMesh.freezeWorldMatrix();
  55099. currentMesh._waitingFreezeWorldMatrix = null;
  55100. }
  55101. else {
  55102. currentMesh.computeWorldMatrix(true);
  55103. }
  55104. }
  55105. // Particles Systems
  55106. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55107. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55108. var parsedParticleSystem = parsedData.particleSystems[index];
  55109. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55110. container.particleSystems.push(ps);
  55111. }
  55112. }
  55113. // Lens flares
  55114. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55115. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55116. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55117. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55118. container.lensFlareSystems.push(lf);
  55119. }
  55120. }
  55121. // Shadows
  55122. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55123. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55124. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55125. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55126. container.shadowGenerators.push(sg);
  55127. }
  55128. }
  55129. // Lights exclusions / inclusions
  55130. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55131. var light_2 = scene.lights[index];
  55132. // Excluded check
  55133. if (light_2._excludedMeshesIds.length > 0) {
  55134. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55135. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55136. if (excludedMesh) {
  55137. light_2.excludedMeshes.push(excludedMesh);
  55138. }
  55139. }
  55140. light_2._excludedMeshesIds = [];
  55141. }
  55142. // Included check
  55143. if (light_2._includedOnlyMeshesIds.length > 0) {
  55144. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55145. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55146. if (includedOnlyMesh) {
  55147. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55148. }
  55149. }
  55150. light_2._includedOnlyMeshesIds = [];
  55151. }
  55152. }
  55153. // Actions (scene)
  55154. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55155. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55156. }
  55157. if (!addToScene) {
  55158. container.removeAllFromScene();
  55159. }
  55160. return container;
  55161. }
  55162. catch (err) {
  55163. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55164. if (onError) {
  55165. onError(msg, err);
  55166. }
  55167. else {
  55168. BABYLON.Tools.Log(msg);
  55169. throw err;
  55170. }
  55171. }
  55172. finally {
  55173. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55174. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55175. }
  55176. }
  55177. return null;
  55178. };
  55179. BABYLON.SceneLoader.RegisterPlugin({
  55180. name: "babylon.js",
  55181. extensions: ".babylon",
  55182. canDirectLoad: function (data) {
  55183. if (data.indexOf("babylon") !== -1) {
  55184. return true;
  55185. }
  55186. return false;
  55187. },
  55188. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55189. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55190. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55191. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55192. // and avoid problems with multiple concurrent .babylon loads.
  55193. var log = "importMesh has failed JSON parse";
  55194. try {
  55195. var parsedData = JSON.parse(data);
  55196. log = "";
  55197. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55198. if (!meshesNames) {
  55199. meshesNames = null;
  55200. }
  55201. else if (!Array.isArray(meshesNames)) {
  55202. meshesNames = [meshesNames];
  55203. }
  55204. var hierarchyIds = new Array();
  55205. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55206. var loadedSkeletonsIds = [];
  55207. var loadedMaterialsIds = [];
  55208. var index;
  55209. var cache;
  55210. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55211. var parsedMesh = parsedData.meshes[index];
  55212. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55213. if (meshesNames !== null) {
  55214. // Remove found mesh name from list.
  55215. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55216. }
  55217. //Geometry?
  55218. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55219. //does the file contain geometries?
  55220. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55221. //find the correct geometry and add it to the scene
  55222. var found = false;
  55223. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55224. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55225. return;
  55226. }
  55227. else {
  55228. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55229. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55230. switch (geometryType) {
  55231. case "boxes":
  55232. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55233. break;
  55234. case "spheres":
  55235. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55236. break;
  55237. case "cylinders":
  55238. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55239. break;
  55240. case "toruses":
  55241. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55242. break;
  55243. case "grounds":
  55244. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55245. break;
  55246. case "planes":
  55247. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55248. break;
  55249. case "torusKnots":
  55250. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55251. break;
  55252. case "vertexData":
  55253. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55254. break;
  55255. }
  55256. found = true;
  55257. }
  55258. });
  55259. }
  55260. });
  55261. if (found === false) {
  55262. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55263. }
  55264. }
  55265. }
  55266. // Material ?
  55267. if (parsedMesh.materialId) {
  55268. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55269. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55270. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55271. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55272. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55273. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55274. var subMatId = parsedMultiMaterial.materials[matIndex];
  55275. loadedMaterialsIds.push(subMatId);
  55276. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55277. log += "\n\tMaterial " + mat.toString(fullDetails);
  55278. }
  55279. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55280. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55281. materialFound = true;
  55282. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55283. break;
  55284. }
  55285. }
  55286. }
  55287. if (materialFound === false) {
  55288. loadedMaterialsIds.push(parsedMesh.materialId);
  55289. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55290. if (!mat) {
  55291. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55292. }
  55293. else {
  55294. log += "\n\tMaterial " + mat.toString(fullDetails);
  55295. }
  55296. }
  55297. }
  55298. // Skeleton ?
  55299. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55300. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55301. if (skeletonAlreadyLoaded === false) {
  55302. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55303. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55304. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55305. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55306. skeletons.push(skeleton);
  55307. loadedSkeletonsIds.push(parsedSkeleton.id);
  55308. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55309. }
  55310. }
  55311. }
  55312. }
  55313. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55314. meshes.push(mesh);
  55315. log += "\n\tMesh " + mesh.toString(fullDetails);
  55316. }
  55317. }
  55318. // Connecting parents
  55319. var currentMesh;
  55320. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55321. currentMesh = scene.meshes[index];
  55322. if (currentMesh._waitingParentId) {
  55323. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55324. currentMesh._waitingParentId = null;
  55325. }
  55326. }
  55327. // freeze and compute world matrix application
  55328. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55329. currentMesh = scene.meshes[index];
  55330. if (currentMesh._waitingFreezeWorldMatrix) {
  55331. currentMesh.freezeWorldMatrix();
  55332. currentMesh._waitingFreezeWorldMatrix = null;
  55333. }
  55334. else {
  55335. currentMesh.computeWorldMatrix(true);
  55336. }
  55337. }
  55338. }
  55339. // Particles
  55340. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55341. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55342. var parsedParticleSystem = parsedData.particleSystems[index];
  55343. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55344. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55345. }
  55346. }
  55347. }
  55348. return true;
  55349. }
  55350. catch (err) {
  55351. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55352. if (onError) {
  55353. onError(msg, err);
  55354. }
  55355. else {
  55356. BABYLON.Tools.Log(msg);
  55357. throw err;
  55358. }
  55359. }
  55360. finally {
  55361. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55362. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55363. }
  55364. }
  55365. return false;
  55366. },
  55367. load: function (scene, data, rootUrl, onError) {
  55368. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55369. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55370. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55371. // and avoid problems with multiple concurrent .babylon loads.
  55372. var log = "importScene has failed JSON parse";
  55373. try {
  55374. var parsedData = JSON.parse(data);
  55375. log = "";
  55376. // Scene
  55377. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55378. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55379. }
  55380. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55381. scene.autoClear = parsedData.autoClear;
  55382. }
  55383. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55384. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55385. }
  55386. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55387. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55388. }
  55389. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55390. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55391. }
  55392. // Fog
  55393. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55394. scene.fogMode = parsedData.fogMode;
  55395. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55396. scene.fogStart = parsedData.fogStart;
  55397. scene.fogEnd = parsedData.fogEnd;
  55398. scene.fogDensity = parsedData.fogDensity;
  55399. log += "\tFog mode for scene: ";
  55400. switch (scene.fogMode) {
  55401. // getters not compiling, so using hardcoded
  55402. case 1:
  55403. log += "exp\n";
  55404. break;
  55405. case 2:
  55406. log += "exp2\n";
  55407. break;
  55408. case 3:
  55409. log += "linear\n";
  55410. break;
  55411. }
  55412. }
  55413. //Physics
  55414. if (parsedData.physicsEnabled) {
  55415. var physicsPlugin;
  55416. if (parsedData.physicsEngine === "cannon") {
  55417. physicsPlugin = new BABYLON.CannonJSPlugin();
  55418. }
  55419. else if (parsedData.physicsEngine === "oimo") {
  55420. physicsPlugin = new BABYLON.OimoJSPlugin();
  55421. }
  55422. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55423. //else - default engine, which is currently oimo
  55424. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55425. scene.enablePhysics(physicsGravity, physicsPlugin);
  55426. }
  55427. // Metadata
  55428. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55429. scene.metadata = parsedData.metadata;
  55430. }
  55431. //collisions, if defined. otherwise, default is true
  55432. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55433. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55434. }
  55435. scene.workerCollisions = !!parsedData.workerCollisions;
  55436. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55437. if (!container) {
  55438. return false;
  55439. }
  55440. if (parsedData.autoAnimate) {
  55441. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55442. }
  55443. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55444. scene.setActiveCameraByID(parsedData.activeCameraID);
  55445. }
  55446. // Environment texture
  55447. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55448. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55449. if (parsedData.createDefaultSkybox === true) {
  55450. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55451. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55452. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55453. }
  55454. }
  55455. // Finish
  55456. return true;
  55457. }
  55458. catch (err) {
  55459. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55460. if (onError) {
  55461. onError(msg, err);
  55462. }
  55463. else {
  55464. BABYLON.Tools.Log(msg);
  55465. throw err;
  55466. }
  55467. }
  55468. finally {
  55469. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55470. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55471. }
  55472. }
  55473. return false;
  55474. },
  55475. loadAssets: function (scene, data, rootUrl, onError) {
  55476. var container = loadAssets(scene, data, rootUrl, onerror);
  55477. return container;
  55478. }
  55479. });
  55480. })(BABYLON || (BABYLON = {}));
  55481. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55482. var BABYLON;
  55483. (function (BABYLON) {
  55484. var FilesInput = /** @class */ (function () {
  55485. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55486. this.onProcessFileCallback = function () { return true; };
  55487. this._engine = engine;
  55488. this._currentScene = scene;
  55489. this._sceneLoadedCallback = sceneLoadedCallback;
  55490. this._progressCallback = progressCallback;
  55491. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55492. this._textureLoadingCallback = textureLoadingCallback;
  55493. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55494. this._onReloadCallback = onReloadCallback;
  55495. this._errorCallback = errorCallback;
  55496. }
  55497. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55498. var _this = this;
  55499. if (elementToMonitor) {
  55500. this._elementToMonitor = elementToMonitor;
  55501. this._dragEnterHandler = function (e) { _this.drag(e); };
  55502. this._dragOverHandler = function (e) { _this.drag(e); };
  55503. this._dropHandler = function (e) { _this.drop(e); };
  55504. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55505. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55506. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55507. }
  55508. };
  55509. FilesInput.prototype.dispose = function () {
  55510. if (!this._elementToMonitor) {
  55511. return;
  55512. }
  55513. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55514. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55515. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55516. };
  55517. FilesInput.prototype.renderFunction = function () {
  55518. if (this._additionalRenderLoopLogicCallback) {
  55519. this._additionalRenderLoopLogicCallback();
  55520. }
  55521. if (this._currentScene) {
  55522. if (this._textureLoadingCallback) {
  55523. var remaining = this._currentScene.getWaitingItemsCount();
  55524. if (remaining > 0) {
  55525. this._textureLoadingCallback(remaining);
  55526. }
  55527. }
  55528. this._currentScene.render();
  55529. }
  55530. };
  55531. FilesInput.prototype.drag = function (e) {
  55532. e.stopPropagation();
  55533. e.preventDefault();
  55534. };
  55535. FilesInput.prototype.drop = function (eventDrop) {
  55536. eventDrop.stopPropagation();
  55537. eventDrop.preventDefault();
  55538. this.loadFiles(eventDrop);
  55539. };
  55540. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55541. var _this = this;
  55542. var reader = folder.createReader();
  55543. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55544. reader.readEntries(function (entries) {
  55545. remaining.count += entries.length;
  55546. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55547. var entry = entries_1[_i];
  55548. if (entry.isFile) {
  55549. entry.file(function (file) {
  55550. file.correctName = relativePath + file.name;
  55551. files.push(file);
  55552. if (--remaining.count === 0) {
  55553. callback();
  55554. }
  55555. });
  55556. }
  55557. else if (entry.isDirectory) {
  55558. _this._traverseFolder(entry, files, remaining, callback);
  55559. }
  55560. }
  55561. if (--remaining.count) {
  55562. callback();
  55563. }
  55564. });
  55565. };
  55566. FilesInput.prototype._processFiles = function (files) {
  55567. for (var i = 0; i < files.length; i++) {
  55568. var name = files[i].correctName.toLowerCase();
  55569. var extension = name.split('.').pop();
  55570. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55571. continue;
  55572. }
  55573. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55574. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55575. this._sceneFileToLoad = files[i];
  55576. }
  55577. else {
  55578. FilesInput.FilesToLoad[name] = files[i];
  55579. }
  55580. }
  55581. };
  55582. FilesInput.prototype.loadFiles = function (event) {
  55583. var _this = this;
  55584. if (this._startingProcessingFilesCallback)
  55585. this._startingProcessingFilesCallback();
  55586. // Handling data transfer via drag'n'drop
  55587. if (event && event.dataTransfer && event.dataTransfer.files) {
  55588. this._filesToLoad = event.dataTransfer.files;
  55589. }
  55590. // Handling files from input files
  55591. if (event && event.target && event.target.files) {
  55592. this._filesToLoad = event.target.files;
  55593. }
  55594. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55595. var files_1 = new Array();
  55596. var folders = [];
  55597. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55598. for (var i = 0; i < this._filesToLoad.length; i++) {
  55599. var fileToLoad = this._filesToLoad[i];
  55600. var name_1 = fileToLoad.name.toLowerCase();
  55601. var entry = void 0;
  55602. fileToLoad.correctName = name_1;
  55603. if (items) {
  55604. var item = items[i];
  55605. if (item.getAsEntry) {
  55606. entry = item.getAsEntry();
  55607. }
  55608. else if (item.webkitGetAsEntry) {
  55609. entry = item.webkitGetAsEntry();
  55610. }
  55611. }
  55612. if (!entry) {
  55613. files_1.push(fileToLoad);
  55614. }
  55615. else {
  55616. if (entry.isDirectory) {
  55617. folders.push(entry);
  55618. }
  55619. else {
  55620. files_1.push(fileToLoad);
  55621. }
  55622. }
  55623. }
  55624. if (folders.length === 0) {
  55625. this._processFiles(files_1);
  55626. this._processReload();
  55627. }
  55628. else {
  55629. var remaining = { count: folders.length };
  55630. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55631. var folder = folders_1[_i];
  55632. this._traverseFolder(folder, files_1, remaining, function () {
  55633. _this._processFiles(files_1);
  55634. if (remaining.count === 0) {
  55635. _this._processReload();
  55636. }
  55637. });
  55638. }
  55639. }
  55640. }
  55641. };
  55642. FilesInput.prototype._processReload = function () {
  55643. if (this._onReloadCallback) {
  55644. this._onReloadCallback(this._sceneFileToLoad);
  55645. }
  55646. else {
  55647. this.reload();
  55648. }
  55649. };
  55650. FilesInput.prototype.reload = function () {
  55651. var _this = this;
  55652. // If a scene file has been provided
  55653. if (this._sceneFileToLoad) {
  55654. if (this._currentScene) {
  55655. if (BABYLON.Tools.errorsCount > 0) {
  55656. BABYLON.Tools.ClearLogCache();
  55657. }
  55658. this._engine.stopRenderLoop();
  55659. this._currentScene.dispose();
  55660. }
  55661. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55662. _this._currentScene = newScene;
  55663. if (_this._sceneLoadedCallback) {
  55664. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55665. }
  55666. // Wait for textures and shaders to be ready
  55667. _this._currentScene.executeWhenReady(function () {
  55668. _this._engine.runRenderLoop(function () {
  55669. _this.renderFunction();
  55670. });
  55671. });
  55672. }, function (progress) {
  55673. if (_this._progressCallback) {
  55674. _this._progressCallback(progress);
  55675. }
  55676. }, function (scene, message) {
  55677. _this._currentScene = scene;
  55678. if (_this._errorCallback) {
  55679. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55680. }
  55681. });
  55682. }
  55683. else {
  55684. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55685. }
  55686. };
  55687. FilesInput.FilesToLoad = {};
  55688. return FilesInput;
  55689. }());
  55690. BABYLON.FilesInput = FilesInput;
  55691. })(BABYLON || (BABYLON = {}));
  55692. //# sourceMappingURL=babylon.filesInput.js.map
  55693. var BABYLON;
  55694. (function (BABYLON) {
  55695. /**
  55696. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55697. * The underlying implementation relies on an associative array to ensure the best performances.
  55698. * The value can be anything including 'null' but except 'undefined'
  55699. */
  55700. var StringDictionary = /** @class */ (function () {
  55701. function StringDictionary() {
  55702. this._count = 0;
  55703. this._data = {};
  55704. }
  55705. /**
  55706. * This will clear this dictionary and copy the content from the 'source' one.
  55707. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55708. * @param source the dictionary to take the content from and copy to this dictionary
  55709. */
  55710. StringDictionary.prototype.copyFrom = function (source) {
  55711. var _this = this;
  55712. this.clear();
  55713. source.forEach(function (t, v) { return _this.add(t, v); });
  55714. };
  55715. /**
  55716. * Get a value based from its key
  55717. * @param key the given key to get the matching value from
  55718. * @return the value if found, otherwise undefined is returned
  55719. */
  55720. StringDictionary.prototype.get = function (key) {
  55721. var val = this._data[key];
  55722. if (val !== undefined) {
  55723. return val;
  55724. }
  55725. return undefined;
  55726. };
  55727. /**
  55728. * Get a value from its key or add it if it doesn't exist.
  55729. * This method will ensure you that a given key/data will be present in the dictionary.
  55730. * @param key the given key to get the matching value from
  55731. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55732. * The factory will only be invoked if there's no data for the given key.
  55733. * @return the value corresponding to the key.
  55734. */
  55735. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55736. var val = this.get(key);
  55737. if (val !== undefined) {
  55738. return val;
  55739. }
  55740. val = factory(key);
  55741. if (val) {
  55742. this.add(key, val);
  55743. }
  55744. return val;
  55745. };
  55746. /**
  55747. * Get a value from its key if present in the dictionary otherwise add it
  55748. * @param key the key to get the value from
  55749. * @param val if there's no such key/value pair in the dictionary add it with this value
  55750. * @return the value corresponding to the key
  55751. */
  55752. StringDictionary.prototype.getOrAdd = function (key, val) {
  55753. var curVal = this.get(key);
  55754. if (curVal !== undefined) {
  55755. return curVal;
  55756. }
  55757. this.add(key, val);
  55758. return val;
  55759. };
  55760. /**
  55761. * Check if there's a given key in the dictionary
  55762. * @param key the key to check for
  55763. * @return true if the key is present, false otherwise
  55764. */
  55765. StringDictionary.prototype.contains = function (key) {
  55766. return this._data[key] !== undefined;
  55767. };
  55768. /**
  55769. * Add a new key and its corresponding value
  55770. * @param key the key to add
  55771. * @param value the value corresponding to the key
  55772. * @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
  55773. */
  55774. StringDictionary.prototype.add = function (key, value) {
  55775. if (this._data[key] !== undefined) {
  55776. return false;
  55777. }
  55778. this._data[key] = value;
  55779. ++this._count;
  55780. return true;
  55781. };
  55782. StringDictionary.prototype.set = function (key, value) {
  55783. if (this._data[key] === undefined) {
  55784. return false;
  55785. }
  55786. this._data[key] = value;
  55787. return true;
  55788. };
  55789. /**
  55790. * Get the element of the given key and remove it from the dictionary
  55791. * @param key
  55792. */
  55793. StringDictionary.prototype.getAndRemove = function (key) {
  55794. var val = this.get(key);
  55795. if (val !== undefined) {
  55796. delete this._data[key];
  55797. --this._count;
  55798. return val;
  55799. }
  55800. return null;
  55801. };
  55802. /**
  55803. * Remove a key/value from the dictionary.
  55804. * @param key the key to remove
  55805. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55806. */
  55807. StringDictionary.prototype.remove = function (key) {
  55808. if (this.contains(key)) {
  55809. delete this._data[key];
  55810. --this._count;
  55811. return true;
  55812. }
  55813. return false;
  55814. };
  55815. /**
  55816. * Clear the whole content of the dictionary
  55817. */
  55818. StringDictionary.prototype.clear = function () {
  55819. this._data = {};
  55820. this._count = 0;
  55821. };
  55822. Object.defineProperty(StringDictionary.prototype, "count", {
  55823. get: function () {
  55824. return this._count;
  55825. },
  55826. enumerable: true,
  55827. configurable: true
  55828. });
  55829. /**
  55830. * Execute a callback on each key/val of the dictionary.
  55831. * Note that you can remove any element in this dictionary in the callback implementation
  55832. * @param callback the callback to execute on a given key/value pair
  55833. */
  55834. StringDictionary.prototype.forEach = function (callback) {
  55835. for (var cur in this._data) {
  55836. var val = this._data[cur];
  55837. callback(cur, val);
  55838. }
  55839. };
  55840. /**
  55841. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55842. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55843. * Note that you can remove any element in this dictionary in the callback implementation
  55844. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55845. */
  55846. StringDictionary.prototype.first = function (callback) {
  55847. for (var cur in this._data) {
  55848. var val = this._data[cur];
  55849. var res = callback(cur, val);
  55850. if (res) {
  55851. return res;
  55852. }
  55853. }
  55854. return null;
  55855. };
  55856. return StringDictionary;
  55857. }());
  55858. BABYLON.StringDictionary = StringDictionary;
  55859. })(BABYLON || (BABYLON = {}));
  55860. //# sourceMappingURL=babylon.stringDictionary.js.map
  55861. var BABYLON;
  55862. (function (BABYLON) {
  55863. var Tags = /** @class */ (function () {
  55864. function Tags() {
  55865. }
  55866. Tags.EnableFor = function (obj) {
  55867. obj._tags = obj._tags || {};
  55868. obj.hasTags = function () {
  55869. return Tags.HasTags(obj);
  55870. };
  55871. obj.addTags = function (tagsString) {
  55872. return Tags.AddTagsTo(obj, tagsString);
  55873. };
  55874. obj.removeTags = function (tagsString) {
  55875. return Tags.RemoveTagsFrom(obj, tagsString);
  55876. };
  55877. obj.matchesTagsQuery = function (tagsQuery) {
  55878. return Tags.MatchesQuery(obj, tagsQuery);
  55879. };
  55880. };
  55881. Tags.DisableFor = function (obj) {
  55882. delete obj._tags;
  55883. delete obj.hasTags;
  55884. delete obj.addTags;
  55885. delete obj.removeTags;
  55886. delete obj.matchesTagsQuery;
  55887. };
  55888. Tags.HasTags = function (obj) {
  55889. if (!obj._tags) {
  55890. return false;
  55891. }
  55892. return !BABYLON.Tools.IsEmpty(obj._tags);
  55893. };
  55894. Tags.GetTags = function (obj, asString) {
  55895. if (asString === void 0) { asString = true; }
  55896. if (!obj._tags) {
  55897. return null;
  55898. }
  55899. if (asString) {
  55900. var tagsArray = [];
  55901. for (var tag in obj._tags) {
  55902. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55903. tagsArray.push(tag);
  55904. }
  55905. }
  55906. return tagsArray.join(" ");
  55907. }
  55908. else {
  55909. return obj._tags;
  55910. }
  55911. };
  55912. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55913. // a tag cannot start with '||', '&&', and '!'
  55914. // it cannot contain whitespaces
  55915. Tags.AddTagsTo = function (obj, tagsString) {
  55916. if (!tagsString) {
  55917. return;
  55918. }
  55919. if (typeof tagsString !== "string") {
  55920. return;
  55921. }
  55922. var tags = tagsString.split(" ");
  55923. tags.forEach(function (tag, index, array) {
  55924. Tags._AddTagTo(obj, tag);
  55925. });
  55926. };
  55927. Tags._AddTagTo = function (obj, tag) {
  55928. tag = tag.trim();
  55929. if (tag === "" || tag === "true" || tag === "false") {
  55930. return;
  55931. }
  55932. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55933. return;
  55934. }
  55935. Tags.EnableFor(obj);
  55936. obj._tags[tag] = true;
  55937. };
  55938. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55939. if (!Tags.HasTags(obj)) {
  55940. return;
  55941. }
  55942. var tags = tagsString.split(" ");
  55943. for (var t in tags) {
  55944. Tags._RemoveTagFrom(obj, tags[t]);
  55945. }
  55946. };
  55947. Tags._RemoveTagFrom = function (obj, tag) {
  55948. delete obj._tags[tag];
  55949. };
  55950. Tags.MatchesQuery = function (obj, tagsQuery) {
  55951. if (tagsQuery === undefined) {
  55952. return true;
  55953. }
  55954. if (tagsQuery === "") {
  55955. return Tags.HasTags(obj);
  55956. }
  55957. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55958. };
  55959. return Tags;
  55960. }());
  55961. BABYLON.Tags = Tags;
  55962. })(BABYLON || (BABYLON = {}));
  55963. //# sourceMappingURL=babylon.tags.js.map
  55964. var BABYLON;
  55965. (function (BABYLON) {
  55966. var AndOrNotEvaluator = /** @class */ (function () {
  55967. function AndOrNotEvaluator() {
  55968. }
  55969. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  55970. if (!query.match(/\([^\(\)]*\)/g)) {
  55971. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  55972. }
  55973. else {
  55974. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  55975. // remove parenthesis
  55976. r = r.slice(1, r.length - 1);
  55977. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  55978. });
  55979. }
  55980. if (query === "true") {
  55981. return true;
  55982. }
  55983. if (query === "false") {
  55984. return false;
  55985. }
  55986. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  55987. };
  55988. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  55989. evaluateCallback = evaluateCallback || (function (r) {
  55990. return r === "true" ? true : false;
  55991. });
  55992. var result;
  55993. var or = parenthesisContent.split("||");
  55994. for (var i in or) {
  55995. if (or.hasOwnProperty(i)) {
  55996. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  55997. var and = ori.split("&&");
  55998. if (and.length > 1) {
  55999. for (var j = 0; j < and.length; ++j) {
  56000. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56001. if (andj !== "true" && andj !== "false") {
  56002. if (andj[0] === "!") {
  56003. result = !evaluateCallback(andj.substring(1));
  56004. }
  56005. else {
  56006. result = evaluateCallback(andj);
  56007. }
  56008. }
  56009. else {
  56010. result = andj === "true" ? true : false;
  56011. }
  56012. if (!result) {
  56013. ori = "false";
  56014. break;
  56015. }
  56016. }
  56017. }
  56018. if (result || ori === "true") {
  56019. result = true;
  56020. break;
  56021. }
  56022. // result equals false (or undefined)
  56023. if (ori !== "true" && ori !== "false") {
  56024. if (ori[0] === "!") {
  56025. result = !evaluateCallback(ori.substring(1));
  56026. }
  56027. else {
  56028. result = evaluateCallback(ori);
  56029. }
  56030. }
  56031. else {
  56032. result = ori === "true" ? true : false;
  56033. }
  56034. }
  56035. }
  56036. // the whole parenthesis scope is replaced by 'true' or 'false'
  56037. return result ? "true" : "false";
  56038. };
  56039. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56040. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56041. // remove whitespaces
  56042. r = r.replace(/[\s]/g, function () { return ""; });
  56043. return r.length % 2 ? "!" : "";
  56044. });
  56045. booleanString = booleanString.trim();
  56046. if (booleanString === "!true") {
  56047. booleanString = "false";
  56048. }
  56049. else if (booleanString === "!false") {
  56050. booleanString = "true";
  56051. }
  56052. return booleanString;
  56053. };
  56054. return AndOrNotEvaluator;
  56055. }());
  56056. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56057. })(BABYLON || (BABYLON = {}));
  56058. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56059. var BABYLON;
  56060. (function (BABYLON) {
  56061. var Database = /** @class */ (function () {
  56062. function Database(urlToScene, callbackManifestChecked) {
  56063. // Handling various flavors of prefixed version of IndexedDB
  56064. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56065. this.callbackManifestChecked = callbackManifestChecked;
  56066. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56067. this.db = null;
  56068. this._enableSceneOffline = false;
  56069. this._enableTexturesOffline = false;
  56070. this.manifestVersionFound = 0;
  56071. this.mustUpdateRessources = false;
  56072. this.hasReachedQuota = false;
  56073. if (!Database.IDBStorageEnabled) {
  56074. this.callbackManifestChecked(true);
  56075. }
  56076. else {
  56077. this.checkManifestFile();
  56078. }
  56079. }
  56080. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56081. get: function () {
  56082. return this._enableSceneOffline;
  56083. },
  56084. enumerable: true,
  56085. configurable: true
  56086. });
  56087. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56088. get: function () {
  56089. return this._enableTexturesOffline;
  56090. },
  56091. enumerable: true,
  56092. configurable: true
  56093. });
  56094. Database.prototype.checkManifestFile = function () {
  56095. var _this = this;
  56096. var noManifestFile = function () {
  56097. _this._enableSceneOffline = false;
  56098. _this._enableTexturesOffline = false;
  56099. _this.callbackManifestChecked(false);
  56100. };
  56101. var timeStampUsed = false;
  56102. var manifestURL = this.currentSceneUrl + ".manifest";
  56103. var xhr = new XMLHttpRequest();
  56104. if (navigator.onLine) {
  56105. // Adding a timestamp to by-pass browsers' cache
  56106. timeStampUsed = true;
  56107. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56108. }
  56109. xhr.open("GET", manifestURL, true);
  56110. xhr.addEventListener("load", function () {
  56111. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56112. try {
  56113. var manifestFile = JSON.parse(xhr.response);
  56114. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56115. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56116. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56117. _this.manifestVersionFound = manifestFile.version;
  56118. }
  56119. if (_this.callbackManifestChecked) {
  56120. _this.callbackManifestChecked(true);
  56121. }
  56122. }
  56123. catch (ex) {
  56124. noManifestFile();
  56125. }
  56126. }
  56127. else {
  56128. noManifestFile();
  56129. }
  56130. }, false);
  56131. xhr.addEventListener("error", function (event) {
  56132. if (timeStampUsed) {
  56133. timeStampUsed = false;
  56134. // Let's retry without the timeStamp
  56135. // It could fail when coupled with HTML5 Offline API
  56136. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56137. xhr.open("GET", retryManifestURL, true);
  56138. xhr.send();
  56139. }
  56140. else {
  56141. noManifestFile();
  56142. }
  56143. }, false);
  56144. try {
  56145. xhr.send();
  56146. }
  56147. catch (ex) {
  56148. BABYLON.Tools.Error("Error on XHR send request.");
  56149. this.callbackManifestChecked(false);
  56150. }
  56151. };
  56152. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56153. var _this = this;
  56154. var handleError = function () {
  56155. _this.isSupported = false;
  56156. if (errorCallback)
  56157. errorCallback();
  56158. };
  56159. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56160. // Your browser doesn't support IndexedDB
  56161. this.isSupported = false;
  56162. if (errorCallback)
  56163. errorCallback();
  56164. }
  56165. else {
  56166. // If the DB hasn't been opened or created yet
  56167. if (!this.db) {
  56168. this.hasReachedQuota = false;
  56169. this.isSupported = true;
  56170. var request = this.idbFactory.open("babylonjs", 1);
  56171. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56172. request.onerror = function (event) {
  56173. handleError();
  56174. };
  56175. // executes when a version change transaction cannot complete due to other active transactions
  56176. request.onblocked = function (event) {
  56177. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56178. handleError();
  56179. };
  56180. // DB has been opened successfully
  56181. request.onsuccess = function (event) {
  56182. _this.db = request.result;
  56183. successCallback();
  56184. };
  56185. // Initialization of the DB. Creating Scenes & Textures stores
  56186. request.onupgradeneeded = function (event) {
  56187. _this.db = (event.target).result;
  56188. if (_this.db) {
  56189. try {
  56190. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56191. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56192. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56193. }
  56194. catch (ex) {
  56195. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56196. handleError();
  56197. }
  56198. }
  56199. };
  56200. }
  56201. else {
  56202. if (successCallback)
  56203. successCallback();
  56204. }
  56205. }
  56206. };
  56207. Database.prototype.loadImageFromDB = function (url, image) {
  56208. var _this = this;
  56209. var completeURL = Database.ReturnFullUrlLocation(url);
  56210. var saveAndLoadImage = function () {
  56211. if (!_this.hasReachedQuota && _this.db !== null) {
  56212. // the texture is not yet in the DB, let's try to save it
  56213. _this._saveImageIntoDBAsync(completeURL, image);
  56214. }
  56215. else {
  56216. image.src = url;
  56217. }
  56218. };
  56219. if (!this.mustUpdateRessources) {
  56220. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56221. }
  56222. else {
  56223. saveAndLoadImage();
  56224. }
  56225. };
  56226. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56227. if (this.isSupported && this.db !== null) {
  56228. var texture;
  56229. var transaction = this.db.transaction(["textures"]);
  56230. transaction.onabort = function (event) {
  56231. image.src = url;
  56232. };
  56233. transaction.oncomplete = function (event) {
  56234. var blobTextureURL;
  56235. if (texture) {
  56236. var URL = window.URL || window.webkitURL;
  56237. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56238. image.onerror = function () {
  56239. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56240. image.src = url;
  56241. };
  56242. image.src = blobTextureURL;
  56243. }
  56244. else {
  56245. notInDBCallback();
  56246. }
  56247. };
  56248. var getRequest = transaction.objectStore("textures").get(url);
  56249. getRequest.onsuccess = function (event) {
  56250. texture = (event.target).result;
  56251. };
  56252. getRequest.onerror = function (event) {
  56253. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56254. image.src = url;
  56255. };
  56256. }
  56257. else {
  56258. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56259. image.src = url;
  56260. }
  56261. };
  56262. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56263. var _this = this;
  56264. if (this.isSupported) {
  56265. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56266. var generateBlobUrl = function () {
  56267. var blobTextureURL;
  56268. if (blob) {
  56269. var URL = window.URL || window.webkitURL;
  56270. try {
  56271. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56272. }
  56273. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56274. catch (ex) {
  56275. blobTextureURL = URL.createObjectURL(blob);
  56276. }
  56277. }
  56278. if (blobTextureURL) {
  56279. image.src = blobTextureURL;
  56280. }
  56281. };
  56282. if (Database.IsUASupportingBlobStorage) {
  56283. var xhr = new XMLHttpRequest(), blob;
  56284. xhr.open("GET", url, true);
  56285. xhr.responseType = "blob";
  56286. xhr.addEventListener("load", function () {
  56287. if (xhr.status === 200 && _this.db) {
  56288. // Blob as response (XHR2)
  56289. blob = xhr.response;
  56290. var transaction = _this.db.transaction(["textures"], "readwrite");
  56291. // the transaction could abort because of a QuotaExceededError error
  56292. transaction.onabort = function (event) {
  56293. try {
  56294. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56295. var srcElement = (event.srcElement || event.target);
  56296. var error = srcElement.error;
  56297. if (error && error.name === "QuotaExceededError") {
  56298. _this.hasReachedQuota = true;
  56299. }
  56300. }
  56301. catch (ex) { }
  56302. generateBlobUrl();
  56303. };
  56304. transaction.oncomplete = function (event) {
  56305. generateBlobUrl();
  56306. };
  56307. var newTexture = { textureUrl: url, data: blob };
  56308. try {
  56309. // Put the blob into the dabase
  56310. var addRequest = transaction.objectStore("textures").put(newTexture);
  56311. addRequest.onsuccess = function (event) {
  56312. };
  56313. addRequest.onerror = function (event) {
  56314. generateBlobUrl();
  56315. };
  56316. }
  56317. catch (ex) {
  56318. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56319. if (ex.code === 25) {
  56320. Database.IsUASupportingBlobStorage = false;
  56321. }
  56322. image.src = url;
  56323. }
  56324. }
  56325. else {
  56326. image.src = url;
  56327. }
  56328. }, false);
  56329. xhr.addEventListener("error", function (event) {
  56330. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56331. image.src = url;
  56332. }, false);
  56333. xhr.send();
  56334. }
  56335. else {
  56336. image.src = url;
  56337. }
  56338. }
  56339. else {
  56340. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56341. image.src = url;
  56342. }
  56343. };
  56344. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56345. var _this = this;
  56346. var updateVersion = function () {
  56347. // the version is not yet in the DB or we need to update it
  56348. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56349. };
  56350. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56351. };
  56352. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56353. var _this = this;
  56354. if (this.isSupported && this.db) {
  56355. var version;
  56356. try {
  56357. var transaction = this.db.transaction(["versions"]);
  56358. transaction.oncomplete = function (event) {
  56359. if (version) {
  56360. // If the version in the JSON file is > than the version in DB
  56361. if (_this.manifestVersionFound > version.data) {
  56362. _this.mustUpdateRessources = true;
  56363. updateInDBCallback();
  56364. }
  56365. else {
  56366. callback(version.data);
  56367. }
  56368. }
  56369. else {
  56370. _this.mustUpdateRessources = true;
  56371. updateInDBCallback();
  56372. }
  56373. };
  56374. transaction.onabort = function (event) {
  56375. callback(-1);
  56376. };
  56377. var getRequest = transaction.objectStore("versions").get(url);
  56378. getRequest.onsuccess = function (event) {
  56379. version = (event.target).result;
  56380. };
  56381. getRequest.onerror = function (event) {
  56382. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56383. callback(-1);
  56384. };
  56385. }
  56386. catch (ex) {
  56387. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56388. callback(-1);
  56389. }
  56390. }
  56391. else {
  56392. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56393. callback(-1);
  56394. }
  56395. };
  56396. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56397. var _this = this;
  56398. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56399. try {
  56400. // Open a transaction to the database
  56401. var transaction = this.db.transaction(["versions"], "readwrite");
  56402. // the transaction could abort because of a QuotaExceededError error
  56403. transaction.onabort = function (event) {
  56404. try {
  56405. var error = event.srcElement['error'];
  56406. if (error && error.name === "QuotaExceededError") {
  56407. _this.hasReachedQuota = true;
  56408. }
  56409. }
  56410. catch (ex) { }
  56411. callback(-1);
  56412. };
  56413. transaction.oncomplete = function (event) {
  56414. callback(_this.manifestVersionFound);
  56415. };
  56416. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56417. // Put the scene into the database
  56418. var addRequest = transaction.objectStore("versions").put(newVersion);
  56419. addRequest.onsuccess = function (event) {
  56420. };
  56421. addRequest.onerror = function (event) {
  56422. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56423. };
  56424. }
  56425. catch (ex) {
  56426. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56427. callback(-1);
  56428. }
  56429. }
  56430. else {
  56431. callback(-1);
  56432. }
  56433. };
  56434. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56435. var _this = this;
  56436. var completeUrl = Database.ReturnFullUrlLocation(url);
  56437. var saveAndLoadFile = function () {
  56438. // the scene is not yet in the DB, let's try to save it
  56439. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56440. };
  56441. this._checkVersionFromDB(completeUrl, function (version) {
  56442. if (version !== -1) {
  56443. if (!_this.mustUpdateRessources) {
  56444. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56445. }
  56446. else {
  56447. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56448. }
  56449. }
  56450. else {
  56451. if (errorCallback) {
  56452. errorCallback();
  56453. }
  56454. }
  56455. });
  56456. };
  56457. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56458. if (this.isSupported && this.db) {
  56459. var targetStore;
  56460. if (url.indexOf(".babylon") !== -1) {
  56461. targetStore = "scenes";
  56462. }
  56463. else {
  56464. targetStore = "textures";
  56465. }
  56466. var file;
  56467. var transaction = this.db.transaction([targetStore]);
  56468. transaction.oncomplete = function (event) {
  56469. if (file) {
  56470. callback(file.data);
  56471. }
  56472. else {
  56473. notInDBCallback();
  56474. }
  56475. };
  56476. transaction.onabort = function (event) {
  56477. notInDBCallback();
  56478. };
  56479. var getRequest = transaction.objectStore(targetStore).get(url);
  56480. getRequest.onsuccess = function (event) {
  56481. file = (event.target).result;
  56482. };
  56483. getRequest.onerror = function (event) {
  56484. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56485. notInDBCallback();
  56486. };
  56487. }
  56488. else {
  56489. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56490. callback();
  56491. }
  56492. };
  56493. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56494. var _this = this;
  56495. if (this.isSupported) {
  56496. var targetStore;
  56497. if (url.indexOf(".babylon") !== -1) {
  56498. targetStore = "scenes";
  56499. }
  56500. else {
  56501. targetStore = "textures";
  56502. }
  56503. // Create XHR
  56504. var xhr = new XMLHttpRequest();
  56505. var fileData;
  56506. xhr.open("GET", url, true);
  56507. if (useArrayBuffer) {
  56508. xhr.responseType = "arraybuffer";
  56509. }
  56510. if (progressCallback) {
  56511. xhr.onprogress = progressCallback;
  56512. }
  56513. xhr.addEventListener("load", function () {
  56514. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56515. // Blob as response (XHR2)
  56516. //fileData = xhr.responseText;
  56517. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56518. if (!_this.hasReachedQuota && _this.db) {
  56519. // Open a transaction to the database
  56520. var transaction = _this.db.transaction([targetStore], "readwrite");
  56521. // the transaction could abort because of a QuotaExceededError error
  56522. transaction.onabort = function (event) {
  56523. try {
  56524. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56525. var error = event.srcElement['error'];
  56526. if (error && error.name === "QuotaExceededError") {
  56527. _this.hasReachedQuota = true;
  56528. }
  56529. }
  56530. catch (ex) { }
  56531. callback(fileData);
  56532. };
  56533. transaction.oncomplete = function (event) {
  56534. callback(fileData);
  56535. };
  56536. var newFile;
  56537. if (targetStore === "scenes") {
  56538. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56539. }
  56540. else {
  56541. newFile = { textureUrl: url, data: fileData };
  56542. }
  56543. try {
  56544. // Put the scene into the database
  56545. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56546. addRequest.onsuccess = function (event) {
  56547. };
  56548. addRequest.onerror = function (event) {
  56549. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56550. };
  56551. }
  56552. catch (ex) {
  56553. callback(fileData);
  56554. }
  56555. }
  56556. else {
  56557. callback(fileData);
  56558. }
  56559. }
  56560. else {
  56561. callback();
  56562. }
  56563. }, false);
  56564. xhr.addEventListener("error", function (event) {
  56565. BABYLON.Tools.Error("error on XHR request.");
  56566. callback();
  56567. }, false);
  56568. xhr.send();
  56569. }
  56570. else {
  56571. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56572. callback();
  56573. }
  56574. };
  56575. Database.IsUASupportingBlobStorage = true;
  56576. Database.IDBStorageEnabled = true;
  56577. Database.parseURL = function (url) {
  56578. var a = document.createElement('a');
  56579. a.href = url;
  56580. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56581. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56582. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56583. return absLocation;
  56584. };
  56585. Database.ReturnFullUrlLocation = function (url) {
  56586. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56587. return (Database.parseURL(window.location.href) + url);
  56588. }
  56589. else {
  56590. return url;
  56591. }
  56592. };
  56593. return Database;
  56594. }());
  56595. BABYLON.Database = Database;
  56596. })(BABYLON || (BABYLON = {}));
  56597. //# sourceMappingURL=babylon.database.js.map
  56598. var BABYLON;
  56599. (function (BABYLON) {
  56600. var FresnelParameters = /** @class */ (function () {
  56601. function FresnelParameters() {
  56602. this._isEnabled = true;
  56603. this.leftColor = BABYLON.Color3.White();
  56604. this.rightColor = BABYLON.Color3.Black();
  56605. this.bias = 0;
  56606. this.power = 1;
  56607. }
  56608. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56609. get: function () {
  56610. return this._isEnabled;
  56611. },
  56612. set: function (value) {
  56613. if (this._isEnabled === value) {
  56614. return;
  56615. }
  56616. this._isEnabled = value;
  56617. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56618. },
  56619. enumerable: true,
  56620. configurable: true
  56621. });
  56622. FresnelParameters.prototype.clone = function () {
  56623. var newFresnelParameters = new FresnelParameters();
  56624. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56625. return newFresnelParameters;
  56626. };
  56627. FresnelParameters.prototype.serialize = function () {
  56628. var serializationObject = {};
  56629. serializationObject.isEnabled = this.isEnabled;
  56630. serializationObject.leftColor = this.leftColor;
  56631. serializationObject.rightColor = this.rightColor;
  56632. serializationObject.bias = this.bias;
  56633. serializationObject.power = this.power;
  56634. return serializationObject;
  56635. };
  56636. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56637. var fresnelParameters = new FresnelParameters();
  56638. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56639. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56640. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56641. fresnelParameters.bias = parsedFresnelParameters.bias;
  56642. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56643. return fresnelParameters;
  56644. };
  56645. return FresnelParameters;
  56646. }());
  56647. BABYLON.FresnelParameters = FresnelParameters;
  56648. })(BABYLON || (BABYLON = {}));
  56649. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56650. var BABYLON;
  56651. (function (BABYLON) {
  56652. var MultiMaterial = /** @class */ (function (_super) {
  56653. __extends(MultiMaterial, _super);
  56654. function MultiMaterial(name, scene) {
  56655. var _this = _super.call(this, name, scene, true) || this;
  56656. scene.multiMaterials.push(_this);
  56657. _this.subMaterials = new Array();
  56658. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56659. return _this;
  56660. }
  56661. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56662. get: function () {
  56663. return this._subMaterials;
  56664. },
  56665. set: function (value) {
  56666. this._subMaterials = value;
  56667. this._hookArray(value);
  56668. },
  56669. enumerable: true,
  56670. configurable: true
  56671. });
  56672. MultiMaterial.prototype._hookArray = function (array) {
  56673. var _this = this;
  56674. var oldPush = array.push;
  56675. array.push = function () {
  56676. var items = [];
  56677. for (var _i = 0; _i < arguments.length; _i++) {
  56678. items[_i] = arguments[_i];
  56679. }
  56680. var result = oldPush.apply(array, items);
  56681. _this._markAllSubMeshesAsTexturesDirty();
  56682. return result;
  56683. };
  56684. var oldSplice = array.splice;
  56685. array.splice = function (index, deleteCount) {
  56686. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56687. _this._markAllSubMeshesAsTexturesDirty();
  56688. return deleted;
  56689. };
  56690. };
  56691. // Properties
  56692. MultiMaterial.prototype.getSubMaterial = function (index) {
  56693. if (index < 0 || index >= this.subMaterials.length) {
  56694. return this.getScene().defaultMaterial;
  56695. }
  56696. return this.subMaterials[index];
  56697. };
  56698. MultiMaterial.prototype.getActiveTextures = function () {
  56699. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56700. if (subMaterial) {
  56701. return subMaterial.getActiveTextures();
  56702. }
  56703. else {
  56704. return [];
  56705. }
  56706. }));
  56707. var _a;
  56708. };
  56709. // Methods
  56710. MultiMaterial.prototype.getClassName = function () {
  56711. return "MultiMaterial";
  56712. };
  56713. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56714. for (var index = 0; index < this.subMaterials.length; index++) {
  56715. var subMaterial = this.subMaterials[index];
  56716. if (subMaterial) {
  56717. if (subMaterial.storeEffectOnSubMeshes) {
  56718. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56719. return false;
  56720. }
  56721. continue;
  56722. }
  56723. if (!subMaterial.isReady(mesh)) {
  56724. return false;
  56725. }
  56726. }
  56727. }
  56728. return true;
  56729. };
  56730. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56731. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56732. for (var index = 0; index < this.subMaterials.length; index++) {
  56733. var subMaterial = null;
  56734. var current = this.subMaterials[index];
  56735. if (cloneChildren && current) {
  56736. subMaterial = current.clone(name + "-" + current.name);
  56737. }
  56738. else {
  56739. subMaterial = this.subMaterials[index];
  56740. }
  56741. newMultiMaterial.subMaterials.push(subMaterial);
  56742. }
  56743. return newMultiMaterial;
  56744. };
  56745. MultiMaterial.prototype.serialize = function () {
  56746. var serializationObject = {};
  56747. serializationObject.name = this.name;
  56748. serializationObject.id = this.id;
  56749. if (BABYLON.Tags) {
  56750. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56751. }
  56752. serializationObject.materials = [];
  56753. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56754. var subMat = this.subMaterials[matIndex];
  56755. if (subMat) {
  56756. serializationObject.materials.push(subMat.id);
  56757. }
  56758. else {
  56759. serializationObject.materials.push(null);
  56760. }
  56761. }
  56762. return serializationObject;
  56763. };
  56764. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56765. var scene = this.getScene();
  56766. if (!scene) {
  56767. return;
  56768. }
  56769. var index = scene.multiMaterials.indexOf(this);
  56770. if (index >= 0) {
  56771. scene.multiMaterials.splice(index, 1);
  56772. }
  56773. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56774. };
  56775. return MultiMaterial;
  56776. }(BABYLON.Material));
  56777. BABYLON.MultiMaterial = MultiMaterial;
  56778. })(BABYLON || (BABYLON = {}));
  56779. //# sourceMappingURL=babylon.multiMaterial.js.map
  56780. var BABYLON;
  56781. (function (BABYLON) {
  56782. var FreeCameraTouchInput = /** @class */ (function () {
  56783. function FreeCameraTouchInput() {
  56784. this._offsetX = null;
  56785. this._offsetY = null;
  56786. this._pointerPressed = new Array();
  56787. this.touchAngularSensibility = 200000.0;
  56788. this.touchMoveSensibility = 250.0;
  56789. }
  56790. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56791. var _this = this;
  56792. var previousPosition = null;
  56793. if (this._pointerInput === undefined) {
  56794. this._onLostFocus = function (evt) {
  56795. _this._offsetX = null;
  56796. _this._offsetY = null;
  56797. };
  56798. this._pointerInput = function (p, s) {
  56799. var evt = p.event;
  56800. if (evt.pointerType === "mouse") {
  56801. return;
  56802. }
  56803. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56804. if (!noPreventDefault) {
  56805. evt.preventDefault();
  56806. }
  56807. _this._pointerPressed.push(evt.pointerId);
  56808. if (_this._pointerPressed.length !== 1) {
  56809. return;
  56810. }
  56811. previousPosition = {
  56812. x: evt.clientX,
  56813. y: evt.clientY
  56814. };
  56815. }
  56816. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56817. if (!noPreventDefault) {
  56818. evt.preventDefault();
  56819. }
  56820. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56821. if (index === -1) {
  56822. return;
  56823. }
  56824. _this._pointerPressed.splice(index, 1);
  56825. if (index != 0) {
  56826. return;
  56827. }
  56828. previousPosition = null;
  56829. _this._offsetX = null;
  56830. _this._offsetY = null;
  56831. }
  56832. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56833. if (!noPreventDefault) {
  56834. evt.preventDefault();
  56835. }
  56836. if (!previousPosition) {
  56837. return;
  56838. }
  56839. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56840. if (index != 0) {
  56841. return;
  56842. }
  56843. _this._offsetX = evt.clientX - previousPosition.x;
  56844. _this._offsetY = -(evt.clientY - previousPosition.y);
  56845. }
  56846. };
  56847. }
  56848. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56849. if (this._onLostFocus) {
  56850. element.addEventListener("blur", this._onLostFocus);
  56851. }
  56852. };
  56853. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56854. if (this._pointerInput && element) {
  56855. if (this._observer) {
  56856. this.camera.getScene().onPointerObservable.remove(this._observer);
  56857. this._observer = null;
  56858. }
  56859. if (this._onLostFocus) {
  56860. element.removeEventListener("blur", this._onLostFocus);
  56861. this._onLostFocus = null;
  56862. }
  56863. this._pointerPressed = [];
  56864. this._offsetX = null;
  56865. this._offsetY = null;
  56866. }
  56867. };
  56868. FreeCameraTouchInput.prototype.checkInputs = function () {
  56869. if (this._offsetX && this._offsetY) {
  56870. var camera = this.camera;
  56871. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56872. if (this._pointerPressed.length > 1) {
  56873. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56874. }
  56875. else {
  56876. var speed = camera._computeLocalCameraSpeed();
  56877. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56878. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56879. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56880. }
  56881. }
  56882. };
  56883. FreeCameraTouchInput.prototype.getClassName = function () {
  56884. return "FreeCameraTouchInput";
  56885. };
  56886. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56887. return "touch";
  56888. };
  56889. __decorate([
  56890. BABYLON.serialize()
  56891. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56892. __decorate([
  56893. BABYLON.serialize()
  56894. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56895. return FreeCameraTouchInput;
  56896. }());
  56897. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56898. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56899. })(BABYLON || (BABYLON = {}));
  56900. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56901. var BABYLON;
  56902. (function (BABYLON) {
  56903. // We're mainly based on the logic defined into the FreeCamera code
  56904. var TouchCamera = /** @class */ (function (_super) {
  56905. __extends(TouchCamera, _super);
  56906. //-- end properties for backward compatibility for inputs
  56907. function TouchCamera(name, position, scene) {
  56908. var _this = _super.call(this, name, position, scene) || this;
  56909. _this.inputs.addTouch();
  56910. _this._setupInputs();
  56911. return _this;
  56912. }
  56913. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56914. //-- Begin properties for backward compatibility for inputs
  56915. get: function () {
  56916. var touch = this.inputs.attached["touch"];
  56917. if (touch)
  56918. return touch.touchAngularSensibility;
  56919. return 0;
  56920. },
  56921. set: function (value) {
  56922. var touch = this.inputs.attached["touch"];
  56923. if (touch)
  56924. touch.touchAngularSensibility = value;
  56925. },
  56926. enumerable: true,
  56927. configurable: true
  56928. });
  56929. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56930. get: function () {
  56931. var touch = this.inputs.attached["touch"];
  56932. if (touch)
  56933. return touch.touchMoveSensibility;
  56934. return 0;
  56935. },
  56936. set: function (value) {
  56937. var touch = this.inputs.attached["touch"];
  56938. if (touch)
  56939. touch.touchMoveSensibility = value;
  56940. },
  56941. enumerable: true,
  56942. configurable: true
  56943. });
  56944. TouchCamera.prototype.getClassName = function () {
  56945. return "TouchCamera";
  56946. };
  56947. TouchCamera.prototype._setupInputs = function () {
  56948. var mouse = this.inputs.attached["mouse"];
  56949. if (mouse) {
  56950. mouse.touchEnabled = false;
  56951. }
  56952. };
  56953. return TouchCamera;
  56954. }(BABYLON.FreeCamera));
  56955. BABYLON.TouchCamera = TouchCamera;
  56956. })(BABYLON || (BABYLON = {}));
  56957. //# sourceMappingURL=babylon.touchCamera.js.map
  56958. var BABYLON;
  56959. (function (BABYLON) {
  56960. var ProceduralTexture = /** @class */ (function (_super) {
  56961. __extends(ProceduralTexture, _super);
  56962. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56963. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56964. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56965. if (isCube === void 0) { isCube = false; }
  56966. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56967. _this.isCube = isCube;
  56968. _this.isEnabled = true;
  56969. _this._currentRefreshId = -1;
  56970. _this._refreshRate = 1;
  56971. _this._vertexBuffers = {};
  56972. _this._uniforms = new Array();
  56973. _this._samplers = new Array();
  56974. _this._textures = {};
  56975. _this._floats = {};
  56976. _this._floatsArrays = {};
  56977. _this._colors3 = {};
  56978. _this._colors4 = {};
  56979. _this._vectors2 = {};
  56980. _this._vectors3 = {};
  56981. _this._matrices = {};
  56982. _this._fallbackTextureUsed = false;
  56983. scene._proceduralTextures.push(_this);
  56984. _this._engine = scene.getEngine();
  56985. _this.name = name;
  56986. _this.isRenderTarget = true;
  56987. _this._size = size;
  56988. _this._generateMipMaps = generateMipMaps;
  56989. _this.setFragment(fragment);
  56990. _this._fallbackTexture = fallbackTexture;
  56991. if (isCube) {
  56992. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  56993. _this.setFloat("face", 0);
  56994. }
  56995. else {
  56996. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  56997. }
  56998. // VBO
  56999. var vertices = [];
  57000. vertices.push(1, 1);
  57001. vertices.push(-1, 1);
  57002. vertices.push(-1, -1);
  57003. vertices.push(1, -1);
  57004. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57005. _this._createIndexBuffer();
  57006. return _this;
  57007. }
  57008. ProceduralTexture.prototype._createIndexBuffer = function () {
  57009. var engine = this._engine;
  57010. // Indices
  57011. var indices = [];
  57012. indices.push(0);
  57013. indices.push(1);
  57014. indices.push(2);
  57015. indices.push(0);
  57016. indices.push(2);
  57017. indices.push(3);
  57018. this._indexBuffer = engine.createIndexBuffer(indices);
  57019. };
  57020. ProceduralTexture.prototype._rebuild = function () {
  57021. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57022. if (vb) {
  57023. vb._rebuild();
  57024. }
  57025. this._createIndexBuffer();
  57026. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57027. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57028. }
  57029. };
  57030. ProceduralTexture.prototype.reset = function () {
  57031. if (this._effect === undefined) {
  57032. return;
  57033. }
  57034. var engine = this._engine;
  57035. engine._releaseEffect(this._effect);
  57036. };
  57037. ProceduralTexture.prototype.isReady = function () {
  57038. var _this = this;
  57039. var engine = this._engine;
  57040. var shaders;
  57041. if (!this._fragment) {
  57042. return false;
  57043. }
  57044. if (this._fallbackTextureUsed) {
  57045. return true;
  57046. }
  57047. if (this._fragment.fragmentElement !== undefined) {
  57048. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57049. }
  57050. else {
  57051. shaders = { vertex: "procedural", fragment: this._fragment };
  57052. }
  57053. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57054. _this.releaseInternalTexture();
  57055. if (_this._fallbackTexture) {
  57056. _this._texture = _this._fallbackTexture._texture;
  57057. if (_this._texture) {
  57058. _this._texture.incrementReferences();
  57059. }
  57060. }
  57061. _this._fallbackTextureUsed = true;
  57062. });
  57063. return this._effect.isReady();
  57064. };
  57065. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57066. this._currentRefreshId = -1;
  57067. };
  57068. ProceduralTexture.prototype.setFragment = function (fragment) {
  57069. this._fragment = fragment;
  57070. };
  57071. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57072. get: function () {
  57073. return this._refreshRate;
  57074. },
  57075. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57076. set: function (value) {
  57077. this._refreshRate = value;
  57078. this.resetRefreshCounter();
  57079. },
  57080. enumerable: true,
  57081. configurable: true
  57082. });
  57083. ProceduralTexture.prototype._shouldRender = function () {
  57084. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57085. return false;
  57086. }
  57087. if (this._fallbackTextureUsed) {
  57088. return false;
  57089. }
  57090. if (this._currentRefreshId === -1) {
  57091. this._currentRefreshId = 1;
  57092. return true;
  57093. }
  57094. if (this.refreshRate === this._currentRefreshId) {
  57095. this._currentRefreshId = 1;
  57096. return true;
  57097. }
  57098. this._currentRefreshId++;
  57099. return false;
  57100. };
  57101. ProceduralTexture.prototype.getRenderSize = function () {
  57102. return this._size;
  57103. };
  57104. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57105. if (this._fallbackTextureUsed) {
  57106. return;
  57107. }
  57108. this.releaseInternalTexture();
  57109. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57110. };
  57111. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57112. if (this._uniforms.indexOf(uniformName) === -1) {
  57113. this._uniforms.push(uniformName);
  57114. }
  57115. };
  57116. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57117. if (this._samplers.indexOf(name) === -1) {
  57118. this._samplers.push(name);
  57119. }
  57120. this._textures[name] = texture;
  57121. return this;
  57122. };
  57123. ProceduralTexture.prototype.setFloat = function (name, value) {
  57124. this._checkUniform(name);
  57125. this._floats[name] = value;
  57126. return this;
  57127. };
  57128. ProceduralTexture.prototype.setFloats = function (name, value) {
  57129. this._checkUniform(name);
  57130. this._floatsArrays[name] = value;
  57131. return this;
  57132. };
  57133. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57134. this._checkUniform(name);
  57135. this._colors3[name] = value;
  57136. return this;
  57137. };
  57138. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57139. this._checkUniform(name);
  57140. this._colors4[name] = value;
  57141. return this;
  57142. };
  57143. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57144. this._checkUniform(name);
  57145. this._vectors2[name] = value;
  57146. return this;
  57147. };
  57148. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57149. this._checkUniform(name);
  57150. this._vectors3[name] = value;
  57151. return this;
  57152. };
  57153. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57154. this._checkUniform(name);
  57155. this._matrices[name] = value;
  57156. return this;
  57157. };
  57158. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57159. var scene = this.getScene();
  57160. if (!scene) {
  57161. return;
  57162. }
  57163. var engine = this._engine;
  57164. // Render
  57165. engine.enableEffect(this._effect);
  57166. engine.setState(false);
  57167. // Texture
  57168. for (var name in this._textures) {
  57169. this._effect.setTexture(name, this._textures[name]);
  57170. }
  57171. // Float
  57172. for (name in this._floats) {
  57173. this._effect.setFloat(name, this._floats[name]);
  57174. }
  57175. // Floats
  57176. for (name in this._floatsArrays) {
  57177. this._effect.setArray(name, this._floatsArrays[name]);
  57178. }
  57179. // Color3
  57180. for (name in this._colors3) {
  57181. this._effect.setColor3(name, this._colors3[name]);
  57182. }
  57183. // Color4
  57184. for (name in this._colors4) {
  57185. var color = this._colors4[name];
  57186. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57187. }
  57188. // Vector2
  57189. for (name in this._vectors2) {
  57190. this._effect.setVector2(name, this._vectors2[name]);
  57191. }
  57192. // Vector3
  57193. for (name in this._vectors3) {
  57194. this._effect.setVector3(name, this._vectors3[name]);
  57195. }
  57196. // Matrix
  57197. for (name in this._matrices) {
  57198. this._effect.setMatrix(name, this._matrices[name]);
  57199. }
  57200. if (!this._texture) {
  57201. return;
  57202. }
  57203. if (this.isCube) {
  57204. for (var face = 0; face < 6; face++) {
  57205. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57206. // VBOs
  57207. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57208. this._effect.setFloat("face", face);
  57209. // Clear
  57210. engine.clear(scene.clearColor, true, true, true);
  57211. // Draw order
  57212. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57213. // Mipmaps
  57214. if (face === 5) {
  57215. engine.generateMipMapsForCubemap(this._texture);
  57216. }
  57217. }
  57218. }
  57219. else {
  57220. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57221. // VBOs
  57222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57223. // Clear
  57224. engine.clear(scene.clearColor, true, true, true);
  57225. // Draw order
  57226. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57227. }
  57228. // Unbind
  57229. engine.unBindFramebuffer(this._texture, this.isCube);
  57230. if (this.onGenerated) {
  57231. this.onGenerated();
  57232. }
  57233. };
  57234. ProceduralTexture.prototype.clone = function () {
  57235. var textureSize = this.getSize();
  57236. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57237. // Base texture
  57238. newTexture.hasAlpha = this.hasAlpha;
  57239. newTexture.level = this.level;
  57240. // RenderTarget Texture
  57241. newTexture.coordinatesMode = this.coordinatesMode;
  57242. return newTexture;
  57243. };
  57244. ProceduralTexture.prototype.dispose = function () {
  57245. var scene = this.getScene();
  57246. if (!scene) {
  57247. return;
  57248. }
  57249. var index = scene._proceduralTextures.indexOf(this);
  57250. if (index >= 0) {
  57251. scene._proceduralTextures.splice(index, 1);
  57252. }
  57253. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57254. if (vertexBuffer) {
  57255. vertexBuffer.dispose();
  57256. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57257. }
  57258. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57259. this._indexBuffer = null;
  57260. }
  57261. _super.prototype.dispose.call(this);
  57262. };
  57263. return ProceduralTexture;
  57264. }(BABYLON.Texture));
  57265. BABYLON.ProceduralTexture = ProceduralTexture;
  57266. })(BABYLON || (BABYLON = {}));
  57267. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57268. var BABYLON;
  57269. (function (BABYLON) {
  57270. var CustomProceduralTexture = /** @class */ (function (_super) {
  57271. __extends(CustomProceduralTexture, _super);
  57272. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57273. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57274. _this._animate = true;
  57275. _this._time = 0;
  57276. _this._texturePath = texturePath;
  57277. //Try to load json
  57278. _this.loadJson(texturePath);
  57279. _this.refreshRate = 1;
  57280. return _this;
  57281. }
  57282. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57283. var _this = this;
  57284. var noConfigFile = function () {
  57285. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57286. try {
  57287. _this.setFragment(_this._texturePath);
  57288. }
  57289. catch (ex) {
  57290. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57291. }
  57292. };
  57293. var configFileUrl = jsonUrl + "/config.json";
  57294. var xhr = new XMLHttpRequest();
  57295. xhr.open("GET", configFileUrl, true);
  57296. xhr.addEventListener("load", function () {
  57297. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57298. try {
  57299. _this._config = JSON.parse(xhr.response);
  57300. _this.updateShaderUniforms();
  57301. _this.updateTextures();
  57302. _this.setFragment(_this._texturePath + "/custom");
  57303. _this._animate = _this._config.animate;
  57304. _this.refreshRate = _this._config.refreshrate;
  57305. }
  57306. catch (ex) {
  57307. noConfigFile();
  57308. }
  57309. }
  57310. else {
  57311. noConfigFile();
  57312. }
  57313. }, false);
  57314. xhr.addEventListener("error", function () {
  57315. noConfigFile();
  57316. }, false);
  57317. try {
  57318. xhr.send();
  57319. }
  57320. catch (ex) {
  57321. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57322. }
  57323. };
  57324. CustomProceduralTexture.prototype.isReady = function () {
  57325. if (!_super.prototype.isReady.call(this)) {
  57326. return false;
  57327. }
  57328. for (var name in this._textures) {
  57329. var texture = this._textures[name];
  57330. if (!texture.isReady()) {
  57331. return false;
  57332. }
  57333. }
  57334. return true;
  57335. };
  57336. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57337. var scene = this.getScene();
  57338. if (this._animate && scene) {
  57339. this._time += scene.getAnimationRatio() * 0.03;
  57340. this.updateShaderUniforms();
  57341. }
  57342. _super.prototype.render.call(this, useCameraPostProcess);
  57343. };
  57344. CustomProceduralTexture.prototype.updateTextures = function () {
  57345. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57346. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57347. }
  57348. };
  57349. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57350. if (this._config) {
  57351. for (var j = 0; j < this._config.uniforms.length; j++) {
  57352. var uniform = this._config.uniforms[j];
  57353. switch (uniform.type) {
  57354. case "float":
  57355. this.setFloat(uniform.name, uniform.value);
  57356. break;
  57357. case "color3":
  57358. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57359. break;
  57360. case "color4":
  57361. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57362. break;
  57363. case "vector2":
  57364. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57365. break;
  57366. case "vector3":
  57367. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57368. break;
  57369. }
  57370. }
  57371. }
  57372. this.setFloat("time", this._time);
  57373. };
  57374. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57375. get: function () {
  57376. return this._animate;
  57377. },
  57378. set: function (value) {
  57379. this._animate = value;
  57380. },
  57381. enumerable: true,
  57382. configurable: true
  57383. });
  57384. return CustomProceduralTexture;
  57385. }(BABYLON.ProceduralTexture));
  57386. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57387. })(BABYLON || (BABYLON = {}));
  57388. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57389. var BABYLON;
  57390. (function (BABYLON) {
  57391. var FreeCameraGamepadInput = /** @class */ (function () {
  57392. function FreeCameraGamepadInput() {
  57393. this.gamepadAngularSensibility = 200;
  57394. this.gamepadMoveSensibility = 40;
  57395. // private members
  57396. this._cameraTransform = BABYLON.Matrix.Identity();
  57397. this._deltaTransform = BABYLON.Vector3.Zero();
  57398. this._vector3 = BABYLON.Vector3.Zero();
  57399. this._vector2 = BABYLON.Vector2.Zero();
  57400. }
  57401. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57402. var _this = this;
  57403. var manager = this.camera.getScene().gamepadManager;
  57404. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57405. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57406. // prioritize XBOX gamepads.
  57407. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57408. _this.gamepad = gamepad;
  57409. }
  57410. }
  57411. });
  57412. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57413. if (_this.gamepad === gamepad) {
  57414. _this.gamepad = null;
  57415. }
  57416. });
  57417. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57418. };
  57419. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57420. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57421. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57422. this.gamepad = null;
  57423. };
  57424. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57425. if (this.gamepad && this.gamepad.leftStick) {
  57426. var camera = this.camera;
  57427. var LSValues = this.gamepad.leftStick;
  57428. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57429. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57430. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57431. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57432. var RSValues = this.gamepad.rightStick;
  57433. if (RSValues) {
  57434. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57435. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57436. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57437. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57438. }
  57439. else {
  57440. RSValues = { x: 0, y: 0 };
  57441. }
  57442. if (!camera.rotationQuaternion) {
  57443. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57444. }
  57445. else {
  57446. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57447. }
  57448. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57449. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57450. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57451. camera.cameraDirection.addInPlace(this._deltaTransform);
  57452. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57453. camera.cameraRotation.addInPlace(this._vector2);
  57454. }
  57455. };
  57456. FreeCameraGamepadInput.prototype.getClassName = function () {
  57457. return "FreeCameraGamepadInput";
  57458. };
  57459. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57460. return "gamepad";
  57461. };
  57462. __decorate([
  57463. BABYLON.serialize()
  57464. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57465. __decorate([
  57466. BABYLON.serialize()
  57467. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57468. return FreeCameraGamepadInput;
  57469. }());
  57470. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57471. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57472. })(BABYLON || (BABYLON = {}));
  57473. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57474. var BABYLON;
  57475. (function (BABYLON) {
  57476. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57477. function ArcRotateCameraGamepadInput() {
  57478. this.gamepadRotationSensibility = 80;
  57479. this.gamepadMoveSensibility = 40;
  57480. }
  57481. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57482. var _this = this;
  57483. var manager = this.camera.getScene().gamepadManager;
  57484. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57485. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57486. // prioritize XBOX gamepads.
  57487. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57488. _this.gamepad = gamepad;
  57489. }
  57490. }
  57491. });
  57492. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57493. if (_this.gamepad === gamepad) {
  57494. _this.gamepad = null;
  57495. }
  57496. });
  57497. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57498. };
  57499. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57500. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57501. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57502. this.gamepad = null;
  57503. };
  57504. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57505. if (this.gamepad) {
  57506. var camera = this.camera;
  57507. var RSValues = this.gamepad.rightStick;
  57508. if (RSValues) {
  57509. if (RSValues.x != 0) {
  57510. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57511. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57512. camera.inertialAlphaOffset += normalizedRX;
  57513. }
  57514. }
  57515. if (RSValues.y != 0) {
  57516. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57517. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57518. camera.inertialBetaOffset += normalizedRY;
  57519. }
  57520. }
  57521. }
  57522. var LSValues = this.gamepad.leftStick;
  57523. if (LSValues && LSValues.y != 0) {
  57524. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57525. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57526. this.camera.inertialRadiusOffset -= normalizedLY;
  57527. }
  57528. }
  57529. }
  57530. };
  57531. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57532. return "ArcRotateCameraGamepadInput";
  57533. };
  57534. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57535. return "gamepad";
  57536. };
  57537. __decorate([
  57538. BABYLON.serialize()
  57539. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57540. __decorate([
  57541. BABYLON.serialize()
  57542. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57543. return ArcRotateCameraGamepadInput;
  57544. }());
  57545. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57546. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57547. })(BABYLON || (BABYLON = {}));
  57548. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57549. var BABYLON;
  57550. (function (BABYLON) {
  57551. var GamepadManager = /** @class */ (function () {
  57552. function GamepadManager(_scene) {
  57553. var _this = this;
  57554. this._scene = _scene;
  57555. this._babylonGamepads = [];
  57556. this._oneGamepadConnected = false;
  57557. this._isMonitoring = false;
  57558. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57559. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57560. this._gamepadEventSupported = false;
  57561. }
  57562. else {
  57563. this._gamepadEventSupported = 'GamepadEvent' in window;
  57564. this._gamepadSupport = (navigator.getGamepads ||
  57565. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57566. }
  57567. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57568. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57569. for (var i in _this._babylonGamepads) {
  57570. var gamepad = _this._babylonGamepads[i];
  57571. if (gamepad && gamepad._isConnected) {
  57572. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57573. }
  57574. }
  57575. });
  57576. this._onGamepadConnectedEvent = function (evt) {
  57577. var gamepad = evt.gamepad;
  57578. if (gamepad.index in _this._babylonGamepads) {
  57579. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57580. return;
  57581. }
  57582. }
  57583. var newGamepad;
  57584. if (_this._babylonGamepads[gamepad.index]) {
  57585. newGamepad = _this._babylonGamepads[gamepad.index];
  57586. newGamepad.browserGamepad = gamepad;
  57587. newGamepad._isConnected = true;
  57588. }
  57589. else {
  57590. newGamepad = _this._addNewGamepad(gamepad);
  57591. }
  57592. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57593. _this._startMonitoringGamepads();
  57594. };
  57595. this._onGamepadDisconnectedEvent = function (evt) {
  57596. var gamepad = evt.gamepad;
  57597. // Remove the gamepad from the list of gamepads to monitor.
  57598. for (var i in _this._babylonGamepads) {
  57599. if (_this._babylonGamepads[i].index === gamepad.index) {
  57600. var disconnectedGamepad = _this._babylonGamepads[i];
  57601. disconnectedGamepad._isConnected = false;
  57602. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57603. break;
  57604. }
  57605. }
  57606. };
  57607. if (this._gamepadSupport) {
  57608. //first add already-connected gamepads
  57609. this._updateGamepadObjects();
  57610. if (this._babylonGamepads.length) {
  57611. this._startMonitoringGamepads();
  57612. }
  57613. // Checking if the gamepad connected event is supported (like in Firefox)
  57614. if (this._gamepadEventSupported) {
  57615. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57616. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57617. }
  57618. else {
  57619. this._startMonitoringGamepads();
  57620. }
  57621. }
  57622. }
  57623. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57624. get: function () {
  57625. return this._babylonGamepads;
  57626. },
  57627. enumerable: true,
  57628. configurable: true
  57629. });
  57630. GamepadManager.prototype.getGamepadByType = function (type) {
  57631. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57632. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57633. var gamepad = _a[_i];
  57634. if (gamepad && gamepad.type === type) {
  57635. return gamepad;
  57636. }
  57637. }
  57638. return null;
  57639. };
  57640. GamepadManager.prototype.dispose = function () {
  57641. if (this._gamepadEventSupported) {
  57642. if (this._onGamepadConnectedEvent) {
  57643. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57644. }
  57645. if (this._onGamepadDisconnectedEvent) {
  57646. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57647. }
  57648. this._onGamepadConnectedEvent = null;
  57649. this._onGamepadDisconnectedEvent = null;
  57650. }
  57651. this._babylonGamepads.forEach(function (gamepad) {
  57652. gamepad.dispose();
  57653. });
  57654. this.onGamepadConnectedObservable.clear();
  57655. this.onGamepadDisconnectedObservable.clear();
  57656. this._oneGamepadConnected = false;
  57657. this._stopMonitoringGamepads();
  57658. this._babylonGamepads = [];
  57659. };
  57660. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57661. if (!this._oneGamepadConnected) {
  57662. this._oneGamepadConnected = true;
  57663. }
  57664. var newGamepad;
  57665. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57666. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57667. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57668. }
  57669. else if (gamepad.pose) {
  57670. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57671. }
  57672. else {
  57673. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57674. }
  57675. this._babylonGamepads[newGamepad.index] = newGamepad;
  57676. return newGamepad;
  57677. };
  57678. GamepadManager.prototype._startMonitoringGamepads = function () {
  57679. if (!this._isMonitoring) {
  57680. this._isMonitoring = true;
  57681. //back-comp
  57682. if (!this._scene) {
  57683. this._checkGamepadsStatus();
  57684. }
  57685. }
  57686. };
  57687. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57688. this._isMonitoring = false;
  57689. };
  57690. GamepadManager.prototype._checkGamepadsStatus = function () {
  57691. var _this = this;
  57692. // Hack to be compatible Chrome
  57693. this._updateGamepadObjects();
  57694. for (var i in this._babylonGamepads) {
  57695. var gamepad = this._babylonGamepads[i];
  57696. if (!gamepad || !gamepad.isConnected) {
  57697. continue;
  57698. }
  57699. gamepad.update();
  57700. }
  57701. if (this._isMonitoring && !this._scene) {
  57702. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57703. }
  57704. };
  57705. // This function is called only on Chrome, which does not properly support
  57706. // connection/disconnection events and forces you to recopy again the gamepad object
  57707. GamepadManager.prototype._updateGamepadObjects = function () {
  57708. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57709. for (var i = 0; i < gamepads.length; i++) {
  57710. if (gamepads[i]) {
  57711. if (!this._babylonGamepads[gamepads[i].index]) {
  57712. var newGamepad = this._addNewGamepad(gamepads[i]);
  57713. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57714. }
  57715. else {
  57716. // Forced to copy again this object for Chrome for unknown reason
  57717. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57718. if (!this._babylonGamepads[i].isConnected) {
  57719. this._babylonGamepads[i]._isConnected = true;
  57720. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57721. }
  57722. }
  57723. }
  57724. }
  57725. };
  57726. return GamepadManager;
  57727. }());
  57728. BABYLON.GamepadManager = GamepadManager;
  57729. })(BABYLON || (BABYLON = {}));
  57730. //# sourceMappingURL=babylon.gamepadManager.js.map
  57731. var BABYLON;
  57732. (function (BABYLON) {
  57733. var StickValues = /** @class */ (function () {
  57734. function StickValues(x, y) {
  57735. this.x = x;
  57736. this.y = y;
  57737. }
  57738. return StickValues;
  57739. }());
  57740. BABYLON.StickValues = StickValues;
  57741. var Gamepad = /** @class */ (function () {
  57742. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57743. if (leftStickX === void 0) { leftStickX = 0; }
  57744. if (leftStickY === void 0) { leftStickY = 1; }
  57745. if (rightStickX === void 0) { rightStickX = 2; }
  57746. if (rightStickY === void 0) { rightStickY = 3; }
  57747. this.id = id;
  57748. this.index = index;
  57749. this.browserGamepad = browserGamepad;
  57750. this._isConnected = true;
  57751. this._invertLeftStickY = false;
  57752. this.type = Gamepad.GAMEPAD;
  57753. this._leftStickAxisX = leftStickX;
  57754. this._leftStickAxisY = leftStickY;
  57755. this._rightStickAxisX = rightStickX;
  57756. this._rightStickAxisY = rightStickY;
  57757. if (this.browserGamepad.axes.length >= 2) {
  57758. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57759. }
  57760. if (this.browserGamepad.axes.length >= 4) {
  57761. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57762. }
  57763. }
  57764. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57765. get: function () {
  57766. return this._isConnected;
  57767. },
  57768. enumerable: true,
  57769. configurable: true
  57770. });
  57771. Gamepad.prototype.onleftstickchanged = function (callback) {
  57772. this._onleftstickchanged = callback;
  57773. };
  57774. Gamepad.prototype.onrightstickchanged = function (callback) {
  57775. this._onrightstickchanged = callback;
  57776. };
  57777. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57778. get: function () {
  57779. return this._leftStick;
  57780. },
  57781. set: function (newValues) {
  57782. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57783. this._onleftstickchanged(newValues);
  57784. }
  57785. this._leftStick = newValues;
  57786. },
  57787. enumerable: true,
  57788. configurable: true
  57789. });
  57790. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57791. get: function () {
  57792. return this._rightStick;
  57793. },
  57794. set: function (newValues) {
  57795. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57796. this._onrightstickchanged(newValues);
  57797. }
  57798. this._rightStick = newValues;
  57799. },
  57800. enumerable: true,
  57801. configurable: true
  57802. });
  57803. Gamepad.prototype.update = function () {
  57804. if (this._leftStick) {
  57805. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57806. if (this._invertLeftStickY) {
  57807. this.leftStick.y *= -1;
  57808. }
  57809. }
  57810. if (this._rightStick) {
  57811. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57812. }
  57813. };
  57814. Gamepad.prototype.dispose = function () {
  57815. };
  57816. Gamepad.GAMEPAD = 0;
  57817. Gamepad.GENERIC = 1;
  57818. Gamepad.XBOX = 2;
  57819. Gamepad.POSE_ENABLED = 3;
  57820. return Gamepad;
  57821. }());
  57822. BABYLON.Gamepad = Gamepad;
  57823. var GenericPad = /** @class */ (function (_super) {
  57824. __extends(GenericPad, _super);
  57825. function GenericPad(id, index, browserGamepad) {
  57826. var _this = _super.call(this, id, index, browserGamepad) || this;
  57827. _this.onButtonDownObservable = new BABYLON.Observable();
  57828. _this.onButtonUpObservable = new BABYLON.Observable();
  57829. _this.type = Gamepad.GENERIC;
  57830. _this._buttons = new Array(browserGamepad.buttons.length);
  57831. return _this;
  57832. }
  57833. GenericPad.prototype.onbuttondown = function (callback) {
  57834. this._onbuttondown = callback;
  57835. };
  57836. GenericPad.prototype.onbuttonup = function (callback) {
  57837. this._onbuttonup = callback;
  57838. };
  57839. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57840. if (newValue !== currentValue) {
  57841. if (newValue === 1) {
  57842. if (this._onbuttondown) {
  57843. this._onbuttondown(buttonIndex);
  57844. }
  57845. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57846. }
  57847. if (newValue === 0) {
  57848. if (this._onbuttonup) {
  57849. this._onbuttonup(buttonIndex);
  57850. }
  57851. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57852. }
  57853. }
  57854. return newValue;
  57855. };
  57856. GenericPad.prototype.update = function () {
  57857. _super.prototype.update.call(this);
  57858. for (var index = 0; index < this._buttons.length; index++) {
  57859. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57860. }
  57861. };
  57862. GenericPad.prototype.dispose = function () {
  57863. _super.prototype.dispose.call(this);
  57864. this.onButtonDownObservable.clear();
  57865. this.onButtonUpObservable.clear();
  57866. };
  57867. return GenericPad;
  57868. }(Gamepad));
  57869. BABYLON.GenericPad = GenericPad;
  57870. })(BABYLON || (BABYLON = {}));
  57871. //# sourceMappingURL=babylon.gamepad.js.map
  57872. var BABYLON;
  57873. (function (BABYLON) {
  57874. var Xbox360Button;
  57875. (function (Xbox360Button) {
  57876. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57877. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57878. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57879. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57880. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57881. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57882. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57883. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57884. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57885. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57886. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57887. var Xbox360Dpad;
  57888. (function (Xbox360Dpad) {
  57889. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57890. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57891. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57892. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57893. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57894. var Xbox360Pad = /** @class */ (function (_super) {
  57895. __extends(Xbox360Pad, _super);
  57896. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57897. if (xboxOne === void 0) { xboxOne = false; }
  57898. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57899. _this._leftTrigger = 0;
  57900. _this._rightTrigger = 0;
  57901. _this.onButtonDownObservable = new BABYLON.Observable();
  57902. _this.onButtonUpObservable = new BABYLON.Observable();
  57903. _this.onPadDownObservable = new BABYLON.Observable();
  57904. _this.onPadUpObservable = new BABYLON.Observable();
  57905. _this._buttonA = 0;
  57906. _this._buttonB = 0;
  57907. _this._buttonX = 0;
  57908. _this._buttonY = 0;
  57909. _this._buttonBack = 0;
  57910. _this._buttonStart = 0;
  57911. _this._buttonLB = 0;
  57912. _this._buttonRB = 0;
  57913. _this._buttonLeftStick = 0;
  57914. _this._buttonRightStick = 0;
  57915. _this._dPadUp = 0;
  57916. _this._dPadDown = 0;
  57917. _this._dPadLeft = 0;
  57918. _this._dPadRight = 0;
  57919. _this._isXboxOnePad = false;
  57920. _this.type = BABYLON.Gamepad.XBOX;
  57921. _this._isXboxOnePad = xboxOne;
  57922. return _this;
  57923. }
  57924. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57925. this._onlefttriggerchanged = callback;
  57926. };
  57927. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57928. this._onrighttriggerchanged = callback;
  57929. };
  57930. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57931. get: function () {
  57932. return this._leftTrigger;
  57933. },
  57934. set: function (newValue) {
  57935. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57936. this._onlefttriggerchanged(newValue);
  57937. }
  57938. this._leftTrigger = newValue;
  57939. },
  57940. enumerable: true,
  57941. configurable: true
  57942. });
  57943. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57944. get: function () {
  57945. return this._rightTrigger;
  57946. },
  57947. set: function (newValue) {
  57948. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57949. this._onrighttriggerchanged(newValue);
  57950. }
  57951. this._rightTrigger = newValue;
  57952. },
  57953. enumerable: true,
  57954. configurable: true
  57955. });
  57956. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57957. this._onbuttondown = callback;
  57958. };
  57959. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57960. this._onbuttonup = callback;
  57961. };
  57962. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57963. this._ondpaddown = callback;
  57964. };
  57965. Xbox360Pad.prototype.ondpadup = function (callback) {
  57966. this._ondpadup = callback;
  57967. };
  57968. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  57969. if (newValue !== currentValue) {
  57970. if (newValue === 1) {
  57971. if (this._onbuttondown) {
  57972. this._onbuttondown(buttonType);
  57973. }
  57974. this.onButtonDownObservable.notifyObservers(buttonType);
  57975. }
  57976. if (newValue === 0) {
  57977. if (this._onbuttonup) {
  57978. this._onbuttonup(buttonType);
  57979. }
  57980. this.onButtonUpObservable.notifyObservers(buttonType);
  57981. }
  57982. }
  57983. return newValue;
  57984. };
  57985. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  57986. if (newValue !== currentValue) {
  57987. if (newValue === 1) {
  57988. if (this._ondpaddown) {
  57989. this._ondpaddown(buttonType);
  57990. }
  57991. this.onPadDownObservable.notifyObservers(buttonType);
  57992. }
  57993. if (newValue === 0) {
  57994. if (this._ondpadup) {
  57995. this._ondpadup(buttonType);
  57996. }
  57997. this.onPadUpObservable.notifyObservers(buttonType);
  57998. }
  57999. }
  58000. return newValue;
  58001. };
  58002. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58003. get: function () {
  58004. return this._buttonA;
  58005. },
  58006. set: function (value) {
  58007. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58008. },
  58009. enumerable: true,
  58010. configurable: true
  58011. });
  58012. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58013. get: function () {
  58014. return this._buttonB;
  58015. },
  58016. set: function (value) {
  58017. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58018. },
  58019. enumerable: true,
  58020. configurable: true
  58021. });
  58022. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58023. get: function () {
  58024. return this._buttonX;
  58025. },
  58026. set: function (value) {
  58027. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58028. },
  58029. enumerable: true,
  58030. configurable: true
  58031. });
  58032. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58033. get: function () {
  58034. return this._buttonY;
  58035. },
  58036. set: function (value) {
  58037. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58038. },
  58039. enumerable: true,
  58040. configurable: true
  58041. });
  58042. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58043. get: function () {
  58044. return this._buttonStart;
  58045. },
  58046. set: function (value) {
  58047. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58048. },
  58049. enumerable: true,
  58050. configurable: true
  58051. });
  58052. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58053. get: function () {
  58054. return this._buttonBack;
  58055. },
  58056. set: function (value) {
  58057. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58058. },
  58059. enumerable: true,
  58060. configurable: true
  58061. });
  58062. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58063. get: function () {
  58064. return this._buttonLB;
  58065. },
  58066. set: function (value) {
  58067. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58068. },
  58069. enumerable: true,
  58070. configurable: true
  58071. });
  58072. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58073. get: function () {
  58074. return this._buttonRB;
  58075. },
  58076. set: function (value) {
  58077. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58078. },
  58079. enumerable: true,
  58080. configurable: true
  58081. });
  58082. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58083. get: function () {
  58084. return this._buttonLeftStick;
  58085. },
  58086. set: function (value) {
  58087. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58088. },
  58089. enumerable: true,
  58090. configurable: true
  58091. });
  58092. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58093. get: function () {
  58094. return this._buttonRightStick;
  58095. },
  58096. set: function (value) {
  58097. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58103. get: function () {
  58104. return this._dPadUp;
  58105. },
  58106. set: function (value) {
  58107. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58108. },
  58109. enumerable: true,
  58110. configurable: true
  58111. });
  58112. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58113. get: function () {
  58114. return this._dPadDown;
  58115. },
  58116. set: function (value) {
  58117. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58118. },
  58119. enumerable: true,
  58120. configurable: true
  58121. });
  58122. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58123. get: function () {
  58124. return this._dPadLeft;
  58125. },
  58126. set: function (value) {
  58127. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58128. },
  58129. enumerable: true,
  58130. configurable: true
  58131. });
  58132. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58133. get: function () {
  58134. return this._dPadRight;
  58135. },
  58136. set: function (value) {
  58137. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58138. },
  58139. enumerable: true,
  58140. configurable: true
  58141. });
  58142. Xbox360Pad.prototype.update = function () {
  58143. _super.prototype.update.call(this);
  58144. if (this._isXboxOnePad) {
  58145. this.buttonA = this.browserGamepad.buttons[0].value;
  58146. this.buttonB = this.browserGamepad.buttons[1].value;
  58147. this.buttonX = this.browserGamepad.buttons[2].value;
  58148. this.buttonY = this.browserGamepad.buttons[3].value;
  58149. this.buttonLB = this.browserGamepad.buttons[4].value;
  58150. this.buttonRB = this.browserGamepad.buttons[5].value;
  58151. this.leftTrigger = this.browserGamepad.axes[2];
  58152. this.rightTrigger = this.browserGamepad.axes[5];
  58153. this.buttonBack = this.browserGamepad.buttons[9].value;
  58154. this.buttonStart = this.browserGamepad.buttons[8].value;
  58155. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58156. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58157. this.dPadUp = this.browserGamepad.buttons[11].value;
  58158. this.dPadDown = this.browserGamepad.buttons[12].value;
  58159. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58160. this.dPadRight = this.browserGamepad.buttons[14].value;
  58161. }
  58162. else {
  58163. this.buttonA = this.browserGamepad.buttons[0].value;
  58164. this.buttonB = this.browserGamepad.buttons[1].value;
  58165. this.buttonX = this.browserGamepad.buttons[2].value;
  58166. this.buttonY = this.browserGamepad.buttons[3].value;
  58167. this.buttonLB = this.browserGamepad.buttons[4].value;
  58168. this.buttonRB = this.browserGamepad.buttons[5].value;
  58169. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58170. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58171. this.buttonBack = this.browserGamepad.buttons[8].value;
  58172. this.buttonStart = this.browserGamepad.buttons[9].value;
  58173. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58174. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58175. this.dPadUp = this.browserGamepad.buttons[12].value;
  58176. this.dPadDown = this.browserGamepad.buttons[13].value;
  58177. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58178. this.dPadRight = this.browserGamepad.buttons[15].value;
  58179. }
  58180. };
  58181. Xbox360Pad.prototype.dispose = function () {
  58182. _super.prototype.dispose.call(this);
  58183. this.onButtonDownObservable.clear();
  58184. this.onButtonUpObservable.clear();
  58185. this.onPadDownObservable.clear();
  58186. this.onPadUpObservable.clear();
  58187. };
  58188. return Xbox360Pad;
  58189. }(BABYLON.Gamepad));
  58190. BABYLON.Xbox360Pad = Xbox360Pad;
  58191. })(BABYLON || (BABYLON = {}));
  58192. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58193. var BABYLON;
  58194. (function (BABYLON) {
  58195. var PoseEnabledControllerType;
  58196. (function (PoseEnabledControllerType) {
  58197. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58198. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58199. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58200. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58201. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58202. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58203. var PoseEnabledControllerHelper = /** @class */ (function () {
  58204. function PoseEnabledControllerHelper() {
  58205. }
  58206. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58207. // Oculus Touch
  58208. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58209. return new BABYLON.OculusTouchController(vrGamepad);
  58210. }
  58211. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58212. return new BABYLON.WindowsMotionController(vrGamepad);
  58213. }
  58214. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58215. return new BABYLON.ViveController(vrGamepad);
  58216. }
  58217. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58218. return new BABYLON.GearVRController(vrGamepad);
  58219. }
  58220. else {
  58221. return new BABYLON.GenericController(vrGamepad);
  58222. }
  58223. };
  58224. return PoseEnabledControllerHelper;
  58225. }());
  58226. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58227. var PoseEnabledController = /** @class */ (function (_super) {
  58228. __extends(PoseEnabledController, _super);
  58229. function PoseEnabledController(browserGamepad) {
  58230. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58231. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58232. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58233. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58234. // Represents device position and rotation in babylon space
  58235. _this.devicePosition = BABYLON.Vector3.Zero();
  58236. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58237. _this.deviceScaleFactor = 1;
  58238. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58239. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58240. _this._workingMatrix = BABYLON.Matrix.Identity();
  58241. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58242. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58243. _this.position = BABYLON.Vector3.Zero();
  58244. _this.rotationQuaternion = new BABYLON.Quaternion();
  58245. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58246. _this._calculatedRotation = new BABYLON.Quaternion();
  58247. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58248. return _this;
  58249. }
  58250. PoseEnabledController.prototype.update = function () {
  58251. _super.prototype.update.call(this);
  58252. var pose = this.browserGamepad.pose;
  58253. this.updateFromDevice(pose);
  58254. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58255. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58256. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58257. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58258. if (this._mesh) {
  58259. this._mesh.position.copyFrom(this.devicePosition);
  58260. if (this._mesh.rotationQuaternion) {
  58261. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58262. }
  58263. }
  58264. };
  58265. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58266. if (poseData) {
  58267. this.rawPose = poseData;
  58268. if (poseData.position) {
  58269. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58270. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58271. this._deviceRoomPosition.z *= -1;
  58272. }
  58273. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58274. this._calculatedPosition.addInPlace(this.position);
  58275. }
  58276. var pose = this.rawPose;
  58277. if (poseData.orientation && pose.orientation) {
  58278. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58279. if (this._mesh) {
  58280. if (this._mesh.getScene().useRightHandedSystem) {
  58281. this._deviceRoomRotationQuaternion.z *= -1;
  58282. this._deviceRoomRotationQuaternion.w *= -1;
  58283. }
  58284. else {
  58285. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58286. }
  58287. }
  58288. // if the camera is set, rotate to the camera's rotation
  58289. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58290. }
  58291. }
  58292. };
  58293. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58294. if (this._mesh) {
  58295. this._mesh.parent = null;
  58296. }
  58297. this._mesh = mesh;
  58298. if (this._poseControlledCamera) {
  58299. this._mesh.parent = this._poseControlledCamera;
  58300. }
  58301. if (!this._mesh.rotationQuaternion) {
  58302. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58303. }
  58304. };
  58305. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58306. this._poseControlledCamera = camera;
  58307. if (this._mesh) {
  58308. this._mesh.parent = this._poseControlledCamera;
  58309. }
  58310. };
  58311. PoseEnabledController.prototype.dispose = function () {
  58312. if (this._mesh) {
  58313. this._mesh.dispose();
  58314. }
  58315. this._mesh = null;
  58316. _super.prototype.dispose.call(this);
  58317. };
  58318. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58319. get: function () {
  58320. return this._mesh;
  58321. },
  58322. enumerable: true,
  58323. configurable: true
  58324. });
  58325. PoseEnabledController.prototype.getForwardRay = function (length) {
  58326. if (length === void 0) { length = 100; }
  58327. if (!this.mesh) {
  58328. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58329. }
  58330. var m = this.mesh.getWorldMatrix();
  58331. var origin = m.getTranslation();
  58332. var forward = new BABYLON.Vector3(0, 0, -1);
  58333. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58334. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58335. return new BABYLON.Ray(origin, direction, length);
  58336. };
  58337. return PoseEnabledController;
  58338. }(BABYLON.Gamepad));
  58339. BABYLON.PoseEnabledController = PoseEnabledController;
  58340. })(BABYLON || (BABYLON = {}));
  58341. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58342. var BABYLON;
  58343. (function (BABYLON) {
  58344. var WebVRController = /** @class */ (function (_super) {
  58345. __extends(WebVRController, _super);
  58346. function WebVRController(vrGamepad) {
  58347. var _this = _super.call(this, vrGamepad) || this;
  58348. // Observables
  58349. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58350. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58351. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58352. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58353. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58354. _this.pad = { x: 0, y: 0 };
  58355. // avoid GC, store state in a tmp object
  58356. _this._changes = {
  58357. pressChanged: false,
  58358. touchChanged: false,
  58359. valueChanged: false,
  58360. changed: false
  58361. };
  58362. _this._buttons = new Array(vrGamepad.buttons.length);
  58363. _this.hand = vrGamepad.hand;
  58364. return _this;
  58365. }
  58366. WebVRController.prototype.onButtonStateChange = function (callback) {
  58367. this._onButtonStateChange = callback;
  58368. };
  58369. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58370. get: function () {
  58371. return this._defaultModel;
  58372. },
  58373. enumerable: true,
  58374. configurable: true
  58375. });
  58376. WebVRController.prototype.update = function () {
  58377. _super.prototype.update.call(this);
  58378. for (var index = 0; index < this._buttons.length; index++) {
  58379. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58380. }
  58381. ;
  58382. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58383. this.pad.x = this.leftStick.x;
  58384. this.pad.y = this.leftStick.y;
  58385. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58386. }
  58387. };
  58388. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58389. if (!newState) {
  58390. newState = {
  58391. pressed: false,
  58392. touched: false,
  58393. value: 0
  58394. };
  58395. }
  58396. if (!currentState) {
  58397. this._buttons[buttonIndex] = {
  58398. pressed: newState.pressed,
  58399. touched: newState.touched,
  58400. value: newState.value
  58401. };
  58402. return;
  58403. }
  58404. this._checkChanges(newState, currentState);
  58405. if (this._changes.changed) {
  58406. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58407. this.handleButtonChange(buttonIndex, newState, this._changes);
  58408. }
  58409. this._buttons[buttonIndex].pressed = newState.pressed;
  58410. this._buttons[buttonIndex].touched = newState.touched;
  58411. // oculus triggers are never 0, thou not touched.
  58412. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58413. };
  58414. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58415. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58416. this._changes.touchChanged = newState.touched !== currentState.touched;
  58417. this._changes.valueChanged = newState.value !== currentState.value;
  58418. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58419. return this._changes;
  58420. };
  58421. WebVRController.prototype.dispose = function () {
  58422. _super.prototype.dispose.call(this);
  58423. this.onTriggerStateChangedObservable.clear();
  58424. this.onMainButtonStateChangedObservable.clear();
  58425. this.onSecondaryButtonStateChangedObservable.clear();
  58426. this.onPadStateChangedObservable.clear();
  58427. this.onPadValuesChangedObservable.clear();
  58428. };
  58429. return WebVRController;
  58430. }(BABYLON.PoseEnabledController));
  58431. BABYLON.WebVRController = WebVRController;
  58432. })(BABYLON || (BABYLON = {}));
  58433. //# sourceMappingURL=babylon.webVRController.js.map
  58434. var BABYLON;
  58435. (function (BABYLON) {
  58436. var OculusTouchController = /** @class */ (function (_super) {
  58437. __extends(OculusTouchController, _super);
  58438. function OculusTouchController(vrGamepad) {
  58439. var _this = _super.call(this, vrGamepad) || this;
  58440. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58441. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58442. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58443. return _this;
  58444. }
  58445. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58446. var _this = this;
  58447. var meshName;
  58448. // Hand
  58449. if (this.hand === 'left') {
  58450. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58451. }
  58452. else {
  58453. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58454. }
  58455. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58456. /*
  58457. Parent Mesh name: oculus_touch_left
  58458. - body
  58459. - trigger
  58460. - thumbstick
  58461. - grip
  58462. - button_y
  58463. - button_x
  58464. - button_enter
  58465. */
  58466. _this._defaultModel = newMeshes[1];
  58467. _this.attachToMesh(_this._defaultModel);
  58468. if (meshLoaded) {
  58469. meshLoaded(_this._defaultModel);
  58470. }
  58471. });
  58472. };
  58473. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58474. // helper getters for left and right hand.
  58475. get: function () {
  58476. if (this.hand === 'right') {
  58477. return this.onMainButtonStateChangedObservable;
  58478. }
  58479. else {
  58480. throw new Error('No A button on left hand');
  58481. }
  58482. },
  58483. enumerable: true,
  58484. configurable: true
  58485. });
  58486. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58487. get: function () {
  58488. if (this.hand === 'right') {
  58489. return this.onSecondaryButtonStateChangedObservable;
  58490. }
  58491. else {
  58492. throw new Error('No B button on left hand');
  58493. }
  58494. },
  58495. enumerable: true,
  58496. configurable: true
  58497. });
  58498. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58499. get: function () {
  58500. if (this.hand === 'left') {
  58501. return this.onMainButtonStateChangedObservable;
  58502. }
  58503. else {
  58504. throw new Error('No X button on right hand');
  58505. }
  58506. },
  58507. enumerable: true,
  58508. configurable: true
  58509. });
  58510. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58511. get: function () {
  58512. if (this.hand === 'left') {
  58513. return this.onSecondaryButtonStateChangedObservable;
  58514. }
  58515. else {
  58516. throw new Error('No Y button on right hand');
  58517. }
  58518. },
  58519. enumerable: true,
  58520. configurable: true
  58521. });
  58522. /*
  58523. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58524. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58525. 2) secondary trigger (same)
  58526. 3) A (right) X (left), touch, pressed = value
  58527. 4) B / Y
  58528. 5) thumb rest
  58529. */
  58530. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58531. var notifyObject = state; //{ state: state, changes: changes };
  58532. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58533. switch (buttonIdx) {
  58534. case 0:
  58535. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58536. return;
  58537. case 1:// index trigger
  58538. if (this._defaultModel) {
  58539. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58540. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58541. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58542. }
  58543. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58544. return;
  58545. case 2:// secondary trigger
  58546. if (this._defaultModel) {
  58547. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58548. }
  58549. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58550. return;
  58551. case 3:
  58552. if (this._defaultModel) {
  58553. if (notifyObject.pressed) {
  58554. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58555. }
  58556. else {
  58557. (this._defaultModel.getChildren()[1]).position.y = 0;
  58558. }
  58559. }
  58560. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58561. return;
  58562. case 4:
  58563. if (this._defaultModel) {
  58564. if (notifyObject.pressed) {
  58565. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58566. }
  58567. else {
  58568. (this._defaultModel.getChildren()[2]).position.y = 0;
  58569. }
  58570. }
  58571. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58572. return;
  58573. case 5:
  58574. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58575. return;
  58576. }
  58577. };
  58578. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58579. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58580. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58581. return OculusTouchController;
  58582. }(BABYLON.WebVRController));
  58583. BABYLON.OculusTouchController = OculusTouchController;
  58584. })(BABYLON || (BABYLON = {}));
  58585. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58586. var BABYLON;
  58587. (function (BABYLON) {
  58588. var ViveController = /** @class */ (function (_super) {
  58589. __extends(ViveController, _super);
  58590. function ViveController(vrGamepad) {
  58591. var _this = _super.call(this, vrGamepad) || this;
  58592. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58593. _this._invertLeftStickY = true;
  58594. return _this;
  58595. }
  58596. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58597. var _this = this;
  58598. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58599. /*
  58600. Parent Mesh name: ViveWand
  58601. - body
  58602. - r_gripper
  58603. - l_gripper
  58604. - menu_button
  58605. - system_button
  58606. - trackpad
  58607. - trigger
  58608. - LED
  58609. */
  58610. _this._defaultModel = newMeshes[1];
  58611. _this.attachToMesh(_this._defaultModel);
  58612. if (meshLoaded) {
  58613. meshLoaded(_this._defaultModel);
  58614. }
  58615. });
  58616. };
  58617. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58618. get: function () {
  58619. return this.onMainButtonStateChangedObservable;
  58620. },
  58621. enumerable: true,
  58622. configurable: true
  58623. });
  58624. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58625. get: function () {
  58626. return this.onMainButtonStateChangedObservable;
  58627. },
  58628. enumerable: true,
  58629. configurable: true
  58630. });
  58631. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58632. get: function () {
  58633. return this.onSecondaryButtonStateChangedObservable;
  58634. },
  58635. enumerable: true,
  58636. configurable: true
  58637. });
  58638. /**
  58639. * Vive mapping:
  58640. * 0: touchpad
  58641. * 1: trigger
  58642. * 2: left AND right buttons
  58643. * 3: menu button
  58644. */
  58645. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58646. var notifyObject = state; //{ state: state, changes: changes };
  58647. switch (buttonIdx) {
  58648. case 0:
  58649. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58650. return;
  58651. case 1:// index trigger
  58652. if (this._defaultModel) {
  58653. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58654. }
  58655. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58656. return;
  58657. case 2:// left AND right button
  58658. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58659. return;
  58660. case 3:
  58661. if (this._defaultModel) {
  58662. if (notifyObject.pressed) {
  58663. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58664. }
  58665. else {
  58666. (this._defaultModel.getChildren()[2]).position.y = 0;
  58667. }
  58668. }
  58669. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58670. return;
  58671. }
  58672. };
  58673. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58674. ViveController.MODEL_FILENAME = 'wand.babylon';
  58675. return ViveController;
  58676. }(BABYLON.WebVRController));
  58677. BABYLON.ViveController = ViveController;
  58678. })(BABYLON || (BABYLON = {}));
  58679. //# sourceMappingURL=babylon.viveController.js.map
  58680. var BABYLON;
  58681. (function (BABYLON) {
  58682. var GenericController = /** @class */ (function (_super) {
  58683. __extends(GenericController, _super);
  58684. function GenericController(vrGamepad) {
  58685. return _super.call(this, vrGamepad) || this;
  58686. }
  58687. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58688. var _this = this;
  58689. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58690. _this._defaultModel = newMeshes[1];
  58691. _this.attachToMesh(_this._defaultModel);
  58692. if (meshLoaded) {
  58693. meshLoaded(_this._defaultModel);
  58694. }
  58695. });
  58696. };
  58697. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58698. console.log("Button id: " + buttonIdx + "state: ");
  58699. console.dir(state);
  58700. };
  58701. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58702. GenericController.MODEL_FILENAME = 'generic.babylon';
  58703. return GenericController;
  58704. }(BABYLON.WebVRController));
  58705. BABYLON.GenericController = GenericController;
  58706. })(BABYLON || (BABYLON = {}));
  58707. //# sourceMappingURL=babylon.genericController.js.map
  58708. var BABYLON;
  58709. (function (BABYLON) {
  58710. var LoadedMeshInfo = /** @class */ (function () {
  58711. function LoadedMeshInfo() {
  58712. this.buttonMeshes = {};
  58713. this.axisMeshes = {};
  58714. }
  58715. return LoadedMeshInfo;
  58716. }());
  58717. var WindowsMotionController = /** @class */ (function (_super) {
  58718. __extends(WindowsMotionController, _super);
  58719. function WindowsMotionController(vrGamepad) {
  58720. var _this = _super.call(this, vrGamepad) || this;
  58721. _this._mapping = {
  58722. // Semantic button names
  58723. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58724. // A mapping of the button name to glTF model node name
  58725. // that should be transformed by button value.
  58726. buttonMeshNames: {
  58727. 'trigger': 'SELECT',
  58728. 'menu': 'MENU',
  58729. 'grip': 'GRASP',
  58730. 'thumbstick': 'THUMBSTICK_PRESS',
  58731. 'trackpad': 'TOUCHPAD_PRESS'
  58732. },
  58733. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58734. buttonObservableNames: {
  58735. 'trigger': 'onTriggerStateChangedObservable',
  58736. 'menu': 'onSecondaryButtonStateChangedObservable',
  58737. 'grip': 'onMainButtonStateChangedObservable',
  58738. 'thumbstick': 'onPadStateChangedObservable',
  58739. 'trackpad': 'onTrackpadChangedObservable'
  58740. },
  58741. // A mapping of the axis name to glTF model node name
  58742. // that should be transformed by axis value.
  58743. // This array mirrors the browserGamepad.axes array, such that
  58744. // the mesh corresponding to axis 0 is in this array index 0.
  58745. axisMeshNames: [
  58746. 'THUMBSTICK_X',
  58747. 'THUMBSTICK_Y',
  58748. 'TOUCHPAD_TOUCH_X',
  58749. 'TOUCHPAD_TOUCH_Y'
  58750. ],
  58751. pointingPoseMeshName: 'POINTING_POSE'
  58752. };
  58753. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58754. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58755. _this.trackpad = { x: 0, y: 0 };
  58756. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58757. _this._loadedMeshInfo = null;
  58758. return _this;
  58759. }
  58760. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58761. get: function () {
  58762. return this.onTriggerStateChangedObservable;
  58763. },
  58764. enumerable: true,
  58765. configurable: true
  58766. });
  58767. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58768. get: function () {
  58769. return this.onSecondaryButtonStateChangedObservable;
  58770. },
  58771. enumerable: true,
  58772. configurable: true
  58773. });
  58774. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58775. get: function () {
  58776. return this.onMainButtonStateChangedObservable;
  58777. },
  58778. enumerable: true,
  58779. configurable: true
  58780. });
  58781. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58782. get: function () {
  58783. return this.onPadStateChangedObservable;
  58784. },
  58785. enumerable: true,
  58786. configurable: true
  58787. });
  58788. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58789. get: function () {
  58790. return this.onTrackpadChangedObservable;
  58791. },
  58792. enumerable: true,
  58793. configurable: true
  58794. });
  58795. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58796. get: function () {
  58797. return this.onTrackpadValuesChangedObservable;
  58798. },
  58799. enumerable: true,
  58800. configurable: true
  58801. });
  58802. /**
  58803. * Called once per frame by the engine.
  58804. */
  58805. WindowsMotionController.prototype.update = function () {
  58806. _super.prototype.update.call(this);
  58807. // Only need to animate axes if there is a loaded mesh
  58808. if (this._loadedMeshInfo) {
  58809. if (this.browserGamepad.axes) {
  58810. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58811. this.trackpad.x = this.browserGamepad["axes"][2];
  58812. this.trackpad.y = this.browserGamepad["axes"][3];
  58813. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58814. }
  58815. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58816. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58817. }
  58818. }
  58819. }
  58820. };
  58821. /**
  58822. * Called once for each button that changed state since the last frame
  58823. * @param buttonIdx Which button index changed
  58824. * @param state New state of the button
  58825. * @param changes Which properties on the state changed since last frame
  58826. */
  58827. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58828. var buttonName = this._mapping.buttons[buttonIdx];
  58829. if (!buttonName) {
  58830. return;
  58831. }
  58832. // Only emit events for buttons that we know how to map from index to name
  58833. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58834. if (observable) {
  58835. observable.notifyObservers(state);
  58836. }
  58837. this.lerpButtonTransform(buttonName, state.value);
  58838. };
  58839. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58840. // If there is no loaded mesh, there is nothing to transform.
  58841. if (!this._loadedMeshInfo) {
  58842. return;
  58843. }
  58844. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58845. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58846. return;
  58847. }
  58848. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58849. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58850. };
  58851. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58852. if (!this._loadedMeshInfo) {
  58853. return;
  58854. }
  58855. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58856. if (!meshInfo) {
  58857. return;
  58858. }
  58859. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58860. return;
  58861. }
  58862. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58863. var lerpValue = axisValue * 0.5 + 0.5;
  58864. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58865. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58866. };
  58867. /**
  58868. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58869. * @param scene scene in which to add meshes
  58870. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58871. */
  58872. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58873. var _this = this;
  58874. if (forceDefault === void 0) { forceDefault = false; }
  58875. var path;
  58876. var filename;
  58877. // Checking if GLB loader is present
  58878. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58879. // Determine the device specific folder based on the ID suffix
  58880. var device = 'default';
  58881. if (this.id && !forceDefault) {
  58882. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58883. device = ((match && match[0]) || device);
  58884. }
  58885. // Hand
  58886. if (this.hand === 'left') {
  58887. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58888. }
  58889. else {
  58890. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58891. }
  58892. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58893. }
  58894. else {
  58895. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58896. path = BABYLON.GenericController.MODEL_BASE_URL;
  58897. filename = BABYLON.GenericController.MODEL_FILENAME;
  58898. }
  58899. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58900. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58901. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58902. if (!_this._loadedMeshInfo) {
  58903. return;
  58904. }
  58905. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58906. _this.attachToMesh(_this._defaultModel);
  58907. if (meshLoaded) {
  58908. meshLoaded(_this._defaultModel);
  58909. }
  58910. }, null, function (scene, message) {
  58911. BABYLON.Tools.Log(message);
  58912. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58913. if (!forceDefault) {
  58914. _this.initControllerMesh(scene, meshLoaded, true);
  58915. }
  58916. });
  58917. };
  58918. /**
  58919. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58920. * can be transformed by button presses and axes values, based on this._mapping.
  58921. *
  58922. * @param scene scene in which the meshes exist
  58923. * @param meshes list of meshes that make up the controller model to process
  58924. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58925. */
  58926. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58927. var loadedMeshInfo = null;
  58928. // Create a new mesh to contain the glTF hierarchy
  58929. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58930. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58931. var childMesh = null;
  58932. for (var i = 0; i < meshes.length; i++) {
  58933. var mesh = meshes[i];
  58934. if (!mesh.parent) {
  58935. // Exclude controller meshes from picking results
  58936. mesh.isPickable = false;
  58937. // Handle root node, attach to the new parentMesh
  58938. childMesh = mesh;
  58939. break;
  58940. }
  58941. }
  58942. if (childMesh) {
  58943. childMesh.setParent(parentMesh);
  58944. // Create our mesh info. Note that this method will always return non-null.
  58945. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58946. }
  58947. else {
  58948. BABYLON.Tools.Warn('Could not find root node in model file.');
  58949. }
  58950. return loadedMeshInfo;
  58951. };
  58952. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58953. var loadedMeshInfo = new LoadedMeshInfo();
  58954. var i;
  58955. loadedMeshInfo.rootNode = rootNode;
  58956. // Reset the caches
  58957. loadedMeshInfo.buttonMeshes = {};
  58958. loadedMeshInfo.axisMeshes = {};
  58959. // Button Meshes
  58960. for (i = 0; i < this._mapping.buttons.length; i++) {
  58961. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58962. if (!buttonMeshName) {
  58963. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58964. continue;
  58965. }
  58966. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  58967. if (!buttonMesh) {
  58968. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  58969. continue;
  58970. }
  58971. var buttonMeshInfo = {
  58972. index: i,
  58973. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  58974. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  58975. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  58976. };
  58977. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  58978. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  58979. }
  58980. else {
  58981. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  58982. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  58983. '(VALUE: ' + !!buttonMeshInfo.value +
  58984. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  58985. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  58986. ')');
  58987. }
  58988. }
  58989. // Axis Meshes
  58990. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  58991. var axisMeshName = this._mapping.axisMeshNames[i];
  58992. if (!axisMeshName) {
  58993. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  58994. continue;
  58995. }
  58996. var axisMesh = getChildByName(rootNode, axisMeshName);
  58997. if (!axisMesh) {
  58998. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  58999. continue;
  59000. }
  59001. var axisMeshInfo = {
  59002. index: i,
  59003. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59004. min: getImmediateChildByName(axisMesh, 'MIN'),
  59005. max: getImmediateChildByName(axisMesh, 'MAX')
  59006. };
  59007. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59008. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59009. }
  59010. else {
  59011. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59012. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59013. '(VALUE: ' + !!axisMeshInfo.value +
  59014. ', MIN: ' + !!axisMeshInfo.min +
  59015. ', MAX:' + !!axisMeshInfo.max +
  59016. ')');
  59017. }
  59018. }
  59019. // Pointing Ray
  59020. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59021. if (!loadedMeshInfo.pointingPoseNode) {
  59022. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59023. }
  59024. return loadedMeshInfo;
  59025. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59026. function getChildByName(node, name) {
  59027. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59028. }
  59029. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59030. function getImmediateChildByName(node, name) {
  59031. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59032. }
  59033. };
  59034. WindowsMotionController.prototype.getForwardRay = function (length) {
  59035. if (length === void 0) { length = 100; }
  59036. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59037. return _super.prototype.getForwardRay.call(this, length);
  59038. }
  59039. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59040. var origin = m.getTranslation();
  59041. var forward = new BABYLON.Vector3(0, 0, -1);
  59042. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59043. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59044. return new BABYLON.Ray(origin, direction, length);
  59045. };
  59046. WindowsMotionController.prototype.dispose = function () {
  59047. _super.prototype.dispose.call(this);
  59048. this.onTrackpadChangedObservable.clear();
  59049. };
  59050. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59051. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59052. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59053. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59054. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59055. return WindowsMotionController;
  59056. }(BABYLON.WebVRController));
  59057. BABYLON.WindowsMotionController = WindowsMotionController;
  59058. })(BABYLON || (BABYLON = {}));
  59059. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59060. var BABYLON;
  59061. (function (BABYLON) {
  59062. var GearVRController = /** @class */ (function (_super) {
  59063. __extends(GearVRController, _super);
  59064. function GearVRController(vrGamepad) {
  59065. var _this = _super.call(this, vrGamepad) || this;
  59066. _this._buttonIndexToObservableNameMap = [
  59067. 'onTrackpadChangedObservable',
  59068. 'onTriggerStateChangedObservable' // Trigger
  59069. ];
  59070. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59071. return _this;
  59072. }
  59073. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59074. var _this = this;
  59075. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59076. _this._defaultModel = newMeshes[1];
  59077. _this.attachToMesh(_this._defaultModel);
  59078. if (meshLoaded) {
  59079. meshLoaded(_this._defaultModel);
  59080. }
  59081. });
  59082. };
  59083. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59084. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59085. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59086. // Only emit events for buttons that we know how to map from index to observable
  59087. var observable = this[observableName];
  59088. if (observable) {
  59089. observable.notifyObservers(state);
  59090. }
  59091. }
  59092. };
  59093. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59094. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59095. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59096. return GearVRController;
  59097. }(BABYLON.WebVRController));
  59098. BABYLON.GearVRController = GearVRController;
  59099. })(BABYLON || (BABYLON = {}));
  59100. //# sourceMappingURL=babylon.gearVRController.js.map
  59101. var BABYLON;
  59102. (function (BABYLON) {
  59103. var FollowCamera = /** @class */ (function (_super) {
  59104. __extends(FollowCamera, _super);
  59105. function FollowCamera(name, position, scene, lockedTarget) {
  59106. if (lockedTarget === void 0) { lockedTarget = null; }
  59107. var _this = _super.call(this, name, position, scene) || this;
  59108. _this.radius = 12;
  59109. _this.rotationOffset = 0;
  59110. _this.heightOffset = 4;
  59111. _this.cameraAcceleration = 0.05;
  59112. _this.maxCameraSpeed = 20;
  59113. _this.lockedTarget = lockedTarget;
  59114. return _this;
  59115. }
  59116. FollowCamera.prototype.getRadians = function (degrees) {
  59117. return degrees * Math.PI / 180;
  59118. };
  59119. FollowCamera.prototype.follow = function (cameraTarget) {
  59120. if (!cameraTarget)
  59121. return;
  59122. var yRotation;
  59123. if (cameraTarget.rotationQuaternion) {
  59124. var rotMatrix = new BABYLON.Matrix();
  59125. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59126. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59127. }
  59128. else {
  59129. yRotation = cameraTarget.rotation.y;
  59130. }
  59131. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59132. var targetPosition = cameraTarget.getAbsolutePosition();
  59133. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59134. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59135. var dx = targetX - this.position.x;
  59136. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59137. var dz = (targetZ) - this.position.z;
  59138. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59139. var vy = dy * this.cameraAcceleration;
  59140. var vz = dz * this.cameraAcceleration * 2;
  59141. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59142. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59143. }
  59144. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59145. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59146. }
  59147. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59148. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59149. }
  59150. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59151. this.setTarget(targetPosition);
  59152. };
  59153. FollowCamera.prototype._checkInputs = function () {
  59154. _super.prototype._checkInputs.call(this);
  59155. if (this.lockedTarget) {
  59156. this.follow(this.lockedTarget);
  59157. }
  59158. };
  59159. FollowCamera.prototype.getClassName = function () {
  59160. return "FollowCamera";
  59161. };
  59162. __decorate([
  59163. BABYLON.serialize()
  59164. ], FollowCamera.prototype, "radius", void 0);
  59165. __decorate([
  59166. BABYLON.serialize()
  59167. ], FollowCamera.prototype, "rotationOffset", void 0);
  59168. __decorate([
  59169. BABYLON.serialize()
  59170. ], FollowCamera.prototype, "heightOffset", void 0);
  59171. __decorate([
  59172. BABYLON.serialize()
  59173. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59174. __decorate([
  59175. BABYLON.serialize()
  59176. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59177. __decorate([
  59178. BABYLON.serializeAsMeshReference("lockedTargetId")
  59179. ], FollowCamera.prototype, "lockedTarget", void 0);
  59180. return FollowCamera;
  59181. }(BABYLON.TargetCamera));
  59182. BABYLON.FollowCamera = FollowCamera;
  59183. var ArcFollowCamera = /** @class */ (function (_super) {
  59184. __extends(ArcFollowCamera, _super);
  59185. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59186. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59187. _this.alpha = alpha;
  59188. _this.beta = beta;
  59189. _this.radius = radius;
  59190. _this.target = target;
  59191. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59192. _this.follow();
  59193. return _this;
  59194. }
  59195. ArcFollowCamera.prototype.follow = function () {
  59196. if (!this.target) {
  59197. return;
  59198. }
  59199. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59200. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59201. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59202. var targetPosition = this.target.getAbsolutePosition();
  59203. this.position = targetPosition.add(this._cartesianCoordinates);
  59204. this.setTarget(targetPosition);
  59205. };
  59206. ArcFollowCamera.prototype._checkInputs = function () {
  59207. _super.prototype._checkInputs.call(this);
  59208. this.follow();
  59209. };
  59210. ArcFollowCamera.prototype.getClassName = function () {
  59211. return "ArcFollowCamera";
  59212. };
  59213. return ArcFollowCamera;
  59214. }(BABYLON.TargetCamera));
  59215. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59216. })(BABYLON || (BABYLON = {}));
  59217. //# sourceMappingURL=babylon.followCamera.js.map
  59218. var BABYLON;
  59219. (function (BABYLON) {
  59220. // We're mainly based on the logic defined into the FreeCamera code
  59221. var UniversalCamera = /** @class */ (function (_super) {
  59222. __extends(UniversalCamera, _super);
  59223. //-- end properties for backward compatibility for inputs
  59224. function UniversalCamera(name, position, scene) {
  59225. var _this = _super.call(this, name, position, scene) || this;
  59226. _this.inputs.addGamepad();
  59227. return _this;
  59228. }
  59229. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59230. //-- Begin properties for backward compatibility for inputs
  59231. get: function () {
  59232. var gamepad = this.inputs.attached["gamepad"];
  59233. if (gamepad)
  59234. return gamepad.gamepadAngularSensibility;
  59235. return 0;
  59236. },
  59237. set: function (value) {
  59238. var gamepad = this.inputs.attached["gamepad"];
  59239. if (gamepad)
  59240. gamepad.gamepadAngularSensibility = value;
  59241. },
  59242. enumerable: true,
  59243. configurable: true
  59244. });
  59245. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59246. get: function () {
  59247. var gamepad = this.inputs.attached["gamepad"];
  59248. if (gamepad)
  59249. return gamepad.gamepadMoveSensibility;
  59250. return 0;
  59251. },
  59252. set: function (value) {
  59253. var gamepad = this.inputs.attached["gamepad"];
  59254. if (gamepad)
  59255. gamepad.gamepadMoveSensibility = value;
  59256. },
  59257. enumerable: true,
  59258. configurable: true
  59259. });
  59260. UniversalCamera.prototype.getClassName = function () {
  59261. return "UniversalCamera";
  59262. };
  59263. return UniversalCamera;
  59264. }(BABYLON.TouchCamera));
  59265. BABYLON.UniversalCamera = UniversalCamera;
  59266. })(BABYLON || (BABYLON = {}));
  59267. //# sourceMappingURL=babylon.universalCamera.js.map
  59268. var BABYLON;
  59269. (function (BABYLON) {
  59270. // We're mainly based on the logic defined into the FreeCamera code
  59271. var GamepadCamera = /** @class */ (function (_super) {
  59272. __extends(GamepadCamera, _super);
  59273. //-- end properties for backward compatibility for inputs
  59274. function GamepadCamera(name, position, scene) {
  59275. return _super.call(this, name, position, scene) || this;
  59276. }
  59277. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59278. //-- Begin properties for backward compatibility for inputs
  59279. get: function () {
  59280. var gamepad = this.inputs.attached["gamepad"];
  59281. if (gamepad)
  59282. return gamepad.gamepadAngularSensibility;
  59283. return 0;
  59284. },
  59285. set: function (value) {
  59286. var gamepad = this.inputs.attached["gamepad"];
  59287. if (gamepad)
  59288. gamepad.gamepadAngularSensibility = value;
  59289. },
  59290. enumerable: true,
  59291. configurable: true
  59292. });
  59293. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59294. get: function () {
  59295. var gamepad = this.inputs.attached["gamepad"];
  59296. if (gamepad)
  59297. return gamepad.gamepadMoveSensibility;
  59298. return 0;
  59299. },
  59300. set: function (value) {
  59301. var gamepad = this.inputs.attached["gamepad"];
  59302. if (gamepad)
  59303. gamepad.gamepadMoveSensibility = value;
  59304. },
  59305. enumerable: true,
  59306. configurable: true
  59307. });
  59308. GamepadCamera.prototype.getClassName = function () {
  59309. return "GamepadCamera";
  59310. };
  59311. return GamepadCamera;
  59312. }(BABYLON.UniversalCamera));
  59313. BABYLON.GamepadCamera = GamepadCamera;
  59314. })(BABYLON || (BABYLON = {}));
  59315. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59316. var BABYLON;
  59317. (function (BABYLON) {
  59318. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59319. function PostProcessRenderPipelineManager() {
  59320. this._renderPipelines = {};
  59321. }
  59322. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59323. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59324. };
  59325. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59326. if (unique === void 0) { unique = false; }
  59327. var renderPipeline = this._renderPipelines[renderPipelineName];
  59328. if (!renderPipeline) {
  59329. return;
  59330. }
  59331. renderPipeline._attachCameras(cameras, unique);
  59332. };
  59333. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59334. var renderPipeline = this._renderPipelines[renderPipelineName];
  59335. if (!renderPipeline) {
  59336. return;
  59337. }
  59338. renderPipeline._detachCameras(cameras);
  59339. };
  59340. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59341. var renderPipeline = this._renderPipelines[renderPipelineName];
  59342. if (!renderPipeline) {
  59343. return;
  59344. }
  59345. renderPipeline._enableEffect(renderEffectName, cameras);
  59346. };
  59347. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59348. var renderPipeline = this._renderPipelines[renderPipelineName];
  59349. if (!renderPipeline) {
  59350. return;
  59351. }
  59352. renderPipeline._disableEffect(renderEffectName, cameras);
  59353. };
  59354. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59355. var renderPipeline = this._renderPipelines[renderPipelineName];
  59356. if (!renderPipeline) {
  59357. return;
  59358. }
  59359. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59360. };
  59361. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59362. var renderPipeline = this._renderPipelines[renderPipelineName];
  59363. if (!renderPipeline) {
  59364. return;
  59365. }
  59366. renderPipeline._disableDisplayOnlyPass(cameras);
  59367. };
  59368. PostProcessRenderPipelineManager.prototype.update = function () {
  59369. for (var renderPipelineName in this._renderPipelines) {
  59370. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59371. var pipeline = this._renderPipelines[renderPipelineName];
  59372. if (!pipeline.isSupported) {
  59373. pipeline.dispose();
  59374. delete this._renderPipelines[renderPipelineName];
  59375. }
  59376. else {
  59377. pipeline._update();
  59378. }
  59379. }
  59380. }
  59381. };
  59382. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59383. for (var renderPipelineName in this._renderPipelines) {
  59384. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59385. var pipeline = this._renderPipelines[renderPipelineName];
  59386. pipeline._rebuild();
  59387. }
  59388. }
  59389. };
  59390. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59391. for (var renderPipelineName in this._renderPipelines) {
  59392. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59393. var pipeline = this._renderPipelines[renderPipelineName];
  59394. pipeline.dispose();
  59395. }
  59396. }
  59397. };
  59398. return PostProcessRenderPipelineManager;
  59399. }());
  59400. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59401. })(BABYLON || (BABYLON = {}));
  59402. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59403. var BABYLON;
  59404. (function (BABYLON) {
  59405. var PostProcessRenderPass = /** @class */ (function () {
  59406. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59407. this._refCount = 0;
  59408. this._name = name;
  59409. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59410. this.setRenderList(renderList);
  59411. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59412. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59413. this._scene = scene;
  59414. this._renderList = renderList;
  59415. }
  59416. // private
  59417. PostProcessRenderPass.prototype._incRefCount = function () {
  59418. if (this._refCount === 0) {
  59419. this._scene.customRenderTargets.push(this._renderTexture);
  59420. }
  59421. return ++this._refCount;
  59422. };
  59423. PostProcessRenderPass.prototype._decRefCount = function () {
  59424. this._refCount--;
  59425. if (this._refCount <= 0) {
  59426. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59427. }
  59428. return this._refCount;
  59429. };
  59430. PostProcessRenderPass.prototype._update = function () {
  59431. this.setRenderList(this._renderList);
  59432. };
  59433. // public
  59434. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59435. this._renderTexture.renderList = renderList;
  59436. };
  59437. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59438. return this._renderTexture;
  59439. };
  59440. return PostProcessRenderPass;
  59441. }());
  59442. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59443. })(BABYLON || (BABYLON = {}));
  59444. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59445. var BABYLON;
  59446. (function (BABYLON) {
  59447. var PostProcessRenderEffect = /** @class */ (function () {
  59448. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59449. this._name = name;
  59450. this._singleInstance = singleInstance || true;
  59451. this._getPostProcess = getPostProcess;
  59452. this._cameras = {};
  59453. this._indicesForCamera = {};
  59454. this._postProcesses = {};
  59455. this._renderPasses = {};
  59456. this._renderEffectAsPasses = {};
  59457. }
  59458. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59459. get: function () {
  59460. for (var index in this._postProcesses) {
  59461. if (!this._postProcesses[index].isSupported) {
  59462. return false;
  59463. }
  59464. }
  59465. return true;
  59466. },
  59467. enumerable: true,
  59468. configurable: true
  59469. });
  59470. PostProcessRenderEffect.prototype._update = function () {
  59471. for (var renderPassName in this._renderPasses) {
  59472. this._renderPasses[renderPassName]._update();
  59473. }
  59474. };
  59475. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59476. this._renderPasses[renderPass._name] = renderPass;
  59477. this._linkParameters();
  59478. };
  59479. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59480. delete this._renderPasses[renderPass._name];
  59481. this._linkParameters();
  59482. };
  59483. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59484. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59485. this._linkParameters();
  59486. };
  59487. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59488. for (var renderPassName in this._renderPasses) {
  59489. if (renderPassName === passName) {
  59490. return this._renderPasses[passName];
  59491. }
  59492. }
  59493. return null;
  59494. };
  59495. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59496. this._renderPasses = {};
  59497. this._linkParameters();
  59498. };
  59499. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59500. var cameraKey;
  59501. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59502. if (!cams) {
  59503. return;
  59504. }
  59505. for (var i = 0; i < cams.length; i++) {
  59506. var camera = cams[i];
  59507. var cameraName = camera.name;
  59508. if (this._singleInstance) {
  59509. cameraKey = 0;
  59510. }
  59511. else {
  59512. cameraKey = cameraName;
  59513. }
  59514. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59515. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59516. if (!this._indicesForCamera[cameraName]) {
  59517. this._indicesForCamera[cameraName] = [];
  59518. }
  59519. this._indicesForCamera[cameraName].push(index);
  59520. if (!this._cameras[cameraName]) {
  59521. this._cameras[cameraName] = camera;
  59522. }
  59523. for (var passName in this._renderPasses) {
  59524. this._renderPasses[passName]._incRefCount();
  59525. }
  59526. }
  59527. this._linkParameters();
  59528. };
  59529. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59530. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59531. if (!cams) {
  59532. return;
  59533. }
  59534. for (var i = 0; i < cams.length; i++) {
  59535. var camera = cams[i];
  59536. var cameraName = camera.name;
  59537. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59538. if (this._cameras[cameraName]) {
  59539. //this._indicesForCamera.splice(index, 1);
  59540. this._cameras[cameraName] = null;
  59541. }
  59542. for (var passName in this._renderPasses) {
  59543. this._renderPasses[passName]._decRefCount();
  59544. }
  59545. }
  59546. };
  59547. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59548. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59549. if (!cams) {
  59550. return;
  59551. }
  59552. for (var i = 0; i < cams.length; i++) {
  59553. var camera = cams[i];
  59554. var cameraName = camera.name;
  59555. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59556. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59557. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59558. }
  59559. }
  59560. for (var passName in this._renderPasses) {
  59561. this._renderPasses[passName]._incRefCount();
  59562. }
  59563. }
  59564. };
  59565. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59566. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59567. if (!cams) {
  59568. return;
  59569. }
  59570. for (var i = 0; i < cams.length; i++) {
  59571. var camera = cams[i];
  59572. var cameraName = camera.Name;
  59573. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59574. for (var passName in this._renderPasses) {
  59575. this._renderPasses[passName]._decRefCount();
  59576. }
  59577. }
  59578. };
  59579. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59580. if (this._singleInstance) {
  59581. return this._postProcesses[0];
  59582. }
  59583. else {
  59584. if (!camera) {
  59585. return null;
  59586. }
  59587. return this._postProcesses[camera.name];
  59588. }
  59589. };
  59590. PostProcessRenderEffect.prototype._linkParameters = function () {
  59591. var _this = this;
  59592. for (var index in this._postProcesses) {
  59593. if (this.applyParameters) {
  59594. this.applyParameters(this._postProcesses[index]);
  59595. }
  59596. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59597. _this._linkTextures(effect);
  59598. });
  59599. }
  59600. };
  59601. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59602. for (var renderPassName in this._renderPasses) {
  59603. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59604. }
  59605. for (var renderEffectName in this._renderEffectAsPasses) {
  59606. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59607. }
  59608. };
  59609. return PostProcessRenderEffect;
  59610. }());
  59611. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59612. })(BABYLON || (BABYLON = {}));
  59613. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59614. var BABYLON;
  59615. (function (BABYLON) {
  59616. var PostProcessRenderPipeline = /** @class */ (function () {
  59617. function PostProcessRenderPipeline(engine, name) {
  59618. this._engine = engine;
  59619. this._name = name;
  59620. this._renderEffects = {};
  59621. this._renderEffectsForIsolatedPass = new Array();
  59622. this._cameras = [];
  59623. }
  59624. PostProcessRenderPipeline.prototype.getClassName = function () {
  59625. return "PostProcessRenderPipeline";
  59626. };
  59627. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59628. get: function () {
  59629. for (var renderEffectName in this._renderEffects) {
  59630. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59631. if (!this._renderEffects[renderEffectName].isSupported) {
  59632. return false;
  59633. }
  59634. }
  59635. }
  59636. return true;
  59637. },
  59638. enumerable: true,
  59639. configurable: true
  59640. });
  59641. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59642. this._renderEffects[renderEffect._name] = renderEffect;
  59643. };
  59644. // private
  59645. PostProcessRenderPipeline.prototype._rebuild = function () {
  59646. };
  59647. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59648. var renderEffects = this._renderEffects[renderEffectName];
  59649. if (!renderEffects) {
  59650. return;
  59651. }
  59652. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59653. };
  59654. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59655. var renderEffects = this._renderEffects[renderEffectName];
  59656. if (!renderEffects) {
  59657. return;
  59658. }
  59659. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59660. };
  59661. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59662. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59663. if (!cams) {
  59664. return;
  59665. }
  59666. var indicesToDelete = [];
  59667. var i;
  59668. for (i = 0; i < cams.length; i++) {
  59669. var camera = cams[i];
  59670. var cameraName = camera.name;
  59671. if (this._cameras.indexOf(camera) === -1) {
  59672. this._cameras[cameraName] = camera;
  59673. }
  59674. else if (unique) {
  59675. indicesToDelete.push(i);
  59676. }
  59677. }
  59678. for (i = 0; i < indicesToDelete.length; i++) {
  59679. cameras.splice(indicesToDelete[i], 1);
  59680. }
  59681. for (var renderEffectName in this._renderEffects) {
  59682. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59683. this._renderEffects[renderEffectName]._attachCameras(cams);
  59684. }
  59685. }
  59686. };
  59687. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59688. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59689. if (!cams) {
  59690. return;
  59691. }
  59692. for (var renderEffectName in this._renderEffects) {
  59693. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59694. this._renderEffects[renderEffectName]._detachCameras(cams);
  59695. }
  59696. }
  59697. for (var i = 0; i < cams.length; i++) {
  59698. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59699. }
  59700. };
  59701. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59702. var _this = this;
  59703. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59704. if (!cams) {
  59705. return;
  59706. }
  59707. var pass = null;
  59708. var renderEffectName;
  59709. for (renderEffectName in this._renderEffects) {
  59710. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59711. pass = this._renderEffects[renderEffectName].getPass(passName);
  59712. if (pass != null) {
  59713. break;
  59714. }
  59715. }
  59716. }
  59717. if (pass === null) {
  59718. return;
  59719. }
  59720. for (renderEffectName in this._renderEffects) {
  59721. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59722. this._renderEffects[renderEffectName]._disable(cams);
  59723. }
  59724. }
  59725. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59726. for (var i = 0; i < cams.length; i++) {
  59727. var camera = cams[i];
  59728. var cameraName = camera.name;
  59729. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59730. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59731. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59732. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59733. }
  59734. };
  59735. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59736. var _this = this;
  59737. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59738. if (!cams) {
  59739. return;
  59740. }
  59741. for (var i = 0; i < cams.length; i++) {
  59742. var camera = cams[i];
  59743. var cameraName = camera.name;
  59744. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59745. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59746. }
  59747. for (var renderEffectName in this._renderEffects) {
  59748. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59749. this._renderEffects[renderEffectName]._enable(cams);
  59750. }
  59751. }
  59752. };
  59753. PostProcessRenderPipeline.prototype._update = function () {
  59754. for (var renderEffectName in this._renderEffects) {
  59755. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59756. this._renderEffects[renderEffectName]._update();
  59757. }
  59758. }
  59759. for (var i = 0; i < this._cameras.length; i++) {
  59760. var cameraName = this._cameras[i].name;
  59761. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59762. this._renderEffectsForIsolatedPass[cameraName]._update();
  59763. }
  59764. }
  59765. };
  59766. PostProcessRenderPipeline.prototype._reset = function () {
  59767. this._renderEffects = {};
  59768. this._renderEffectsForIsolatedPass = new Array();
  59769. };
  59770. PostProcessRenderPipeline.prototype.dispose = function () {
  59771. // Must be implemented by children
  59772. };
  59773. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59774. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59775. __decorate([
  59776. BABYLON.serialize()
  59777. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59778. return PostProcessRenderPipeline;
  59779. }());
  59780. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59781. })(BABYLON || (BABYLON = {}));
  59782. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59783. var BABYLON;
  59784. (function (BABYLON) {
  59785. var DepthRenderer = /** @class */ (function () {
  59786. function DepthRenderer(scene, type) {
  59787. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59788. var _this = this;
  59789. this._scene = scene;
  59790. var engine = scene.getEngine();
  59791. // Render target
  59792. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59793. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59794. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59795. this._depthMap.refreshRate = 1;
  59796. this._depthMap.renderParticles = false;
  59797. this._depthMap.renderList = null;
  59798. // set default depth value to 1.0 (far away)
  59799. this._depthMap.onClearObservable.add(function (engine) {
  59800. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59801. });
  59802. // Custom render function
  59803. var renderSubMesh = function (subMesh) {
  59804. var mesh = subMesh.getRenderingMesh();
  59805. var scene = _this._scene;
  59806. var engine = scene.getEngine();
  59807. var material = subMesh.getMaterial();
  59808. if (!material) {
  59809. return;
  59810. }
  59811. // Culling and reverse (right handed system)
  59812. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59813. // Managing instances
  59814. var batch = mesh._getInstancesRenderList(subMesh._id);
  59815. if (batch.mustReturn) {
  59816. return;
  59817. }
  59818. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59819. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59820. engine.enableEffect(_this._effect);
  59821. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59822. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59823. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59824. // Alpha test
  59825. if (material && material.needAlphaTesting()) {
  59826. var alphaTexture = material.getAlphaTestTexture();
  59827. if (alphaTexture) {
  59828. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59829. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59830. }
  59831. }
  59832. // Bones
  59833. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59834. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59835. }
  59836. // Draw
  59837. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59838. }
  59839. };
  59840. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59841. var index;
  59842. if (depthOnlySubMeshes.length) {
  59843. engine.setColorWrite(false);
  59844. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59845. renderSubMesh(depthOnlySubMeshes.data[index]);
  59846. }
  59847. engine.setColorWrite(true);
  59848. }
  59849. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59850. renderSubMesh(opaqueSubMeshes.data[index]);
  59851. }
  59852. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59853. renderSubMesh(alphaTestSubMeshes.data[index]);
  59854. }
  59855. };
  59856. }
  59857. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59858. var material = subMesh.getMaterial();
  59859. if (material.disableDepthWrite) {
  59860. return false;
  59861. }
  59862. var defines = [];
  59863. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59864. var mesh = subMesh.getMesh();
  59865. // Alpha test
  59866. if (material && material.needAlphaTesting()) {
  59867. defines.push("#define ALPHATEST");
  59868. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59869. attribs.push(BABYLON.VertexBuffer.UVKind);
  59870. defines.push("#define UV1");
  59871. }
  59872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59873. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59874. defines.push("#define UV2");
  59875. }
  59876. }
  59877. // Bones
  59878. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59879. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59880. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59881. if (mesh.numBoneInfluencers > 4) {
  59882. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59883. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59884. }
  59885. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59886. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59887. }
  59888. else {
  59889. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59890. }
  59891. // Instances
  59892. if (useInstances) {
  59893. defines.push("#define INSTANCES");
  59894. attribs.push("world0");
  59895. attribs.push("world1");
  59896. attribs.push("world2");
  59897. attribs.push("world3");
  59898. }
  59899. // Get correct effect
  59900. var join = defines.join("\n");
  59901. if (this._cachedDefines !== join) {
  59902. this._cachedDefines = join;
  59903. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59904. }
  59905. return this._effect.isReady();
  59906. };
  59907. DepthRenderer.prototype.getDepthMap = function () {
  59908. return this._depthMap;
  59909. };
  59910. // Methods
  59911. DepthRenderer.prototype.dispose = function () {
  59912. this._depthMap.dispose();
  59913. };
  59914. return DepthRenderer;
  59915. }());
  59916. BABYLON.DepthRenderer = DepthRenderer;
  59917. })(BABYLON || (BABYLON = {}));
  59918. //# sourceMappingURL=babylon.depthRenderer.js.map
  59919. var BABYLON;
  59920. (function (BABYLON) {
  59921. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59922. __extends(SSAORenderingPipeline, _super);
  59923. /**
  59924. * @constructor
  59925. * @param {string} name - The rendering pipeline name
  59926. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59927. * @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 }
  59928. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59929. */
  59930. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59931. var _this = _super.call(this, scene.getEngine(), name) || this;
  59932. // Members
  59933. /**
  59934. * The PassPostProcess id in the pipeline that contains the original scene color
  59935. * @type {string}
  59936. */
  59937. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59938. /**
  59939. * The SSAO PostProcess id in the pipeline
  59940. * @type {string}
  59941. */
  59942. _this.SSAORenderEffect = "SSAORenderEffect";
  59943. /**
  59944. * The horizontal blur PostProcess id in the pipeline
  59945. * @type {string}
  59946. */
  59947. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59948. /**
  59949. * The vertical blur PostProcess id in the pipeline
  59950. * @type {string}
  59951. */
  59952. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59953. /**
  59954. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59955. * @type {string}
  59956. */
  59957. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59958. /**
  59959. * The output strength of the SSAO post-process. Default value is 1.0.
  59960. * @type {number}
  59961. */
  59962. _this.totalStrength = 1.0;
  59963. /**
  59964. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  59965. * @type {number}
  59966. */
  59967. _this.radius = 0.0001;
  59968. /**
  59969. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  59970. * Must not be equal to fallOff and superior to fallOff.
  59971. * Default value is 0.975
  59972. * @type {number}
  59973. */
  59974. _this.area = 0.0075;
  59975. /**
  59976. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  59977. * Must not be equal to area and inferior to area.
  59978. * Default value is 0.0
  59979. * @type {number}
  59980. */
  59981. _this.fallOff = 0.000001;
  59982. /**
  59983. * The base color of the SSAO post-process
  59984. * The final result is "base + ssao" between [0, 1]
  59985. * @type {number}
  59986. */
  59987. _this.base = 0.5;
  59988. _this._firstUpdate = true;
  59989. _this._scene = scene;
  59990. // Set up assets
  59991. _this._createRandomTexture();
  59992. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59993. var ssaoRatio = ratio.ssaoRatio || ratio;
  59994. var combineRatio = ratio.combineRatio || ratio;
  59995. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59996. _this._createSSAOPostProcess(ssaoRatio);
  59997. _this._createBlurPostProcess(ssaoRatio);
  59998. _this._createSSAOCombinePostProcess(combineRatio);
  59999. // Set up pipeline
  60000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60002. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60003. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60004. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60005. // Finish
  60006. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60007. if (cameras)
  60008. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60009. return _this;
  60010. }
  60011. // Public Methods
  60012. /**
  60013. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60014. */
  60015. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60016. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60017. for (var i = 0; i < this._scene.cameras.length; i++) {
  60018. var camera = this._scene.cameras[i];
  60019. this._originalColorPostProcess.dispose(camera);
  60020. this._ssaoPostProcess.dispose(camera);
  60021. this._blurHPostProcess.dispose(camera);
  60022. this._blurVPostProcess.dispose(camera);
  60023. this._ssaoCombinePostProcess.dispose(camera);
  60024. }
  60025. this._randomTexture.dispose();
  60026. if (disableDepthRender)
  60027. this._scene.disableDepthRenderer();
  60028. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60029. _super.prototype.dispose.call(this);
  60030. };
  60031. // Private Methods
  60032. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60033. var _this = this;
  60034. var size = 16;
  60035. 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);
  60036. 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);
  60037. this._blurHPostProcess.onActivateObservable.add(function () {
  60038. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60039. _this._blurHPostProcess.kernel = size * dw;
  60040. });
  60041. this._blurVPostProcess.onActivateObservable.add(function () {
  60042. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60043. _this._blurVPostProcess.kernel = size * dw;
  60044. });
  60045. };
  60046. SSAORenderingPipeline.prototype._rebuild = function () {
  60047. this._firstUpdate = true;
  60048. _super.prototype._rebuild.call(this);
  60049. };
  60050. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60051. var _this = this;
  60052. var numSamples = 16;
  60053. var sampleSphere = [
  60054. 0.5381, 0.1856, -0.4319,
  60055. 0.1379, 0.2486, 0.4430,
  60056. 0.3371, 0.5679, -0.0057,
  60057. -0.6999, -0.0451, -0.0019,
  60058. 0.0689, -0.1598, -0.8547,
  60059. 0.0560, 0.0069, -0.1843,
  60060. -0.0146, 0.1402, 0.0762,
  60061. 0.0100, -0.1924, -0.0344,
  60062. -0.3577, -0.5301, -0.4358,
  60063. -0.3169, 0.1063, 0.0158,
  60064. 0.0103, -0.5869, 0.0046,
  60065. -0.0897, -0.4940, 0.3287,
  60066. 0.7119, -0.0154, -0.0918,
  60067. -0.0533, 0.0596, -0.5411,
  60068. 0.0352, -0.0631, 0.5460,
  60069. -0.4776, 0.2847, -0.0271
  60070. ];
  60071. var samplesFactor = 1.0 / numSamples;
  60072. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60073. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60074. "area", "fallOff", "base", "range", "viewport"
  60075. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60076. this._ssaoPostProcess.onApply = function (effect) {
  60077. if (_this._firstUpdate) {
  60078. effect.setArray3("sampleSphere", sampleSphere);
  60079. effect.setFloat("samplesFactor", samplesFactor);
  60080. effect.setFloat("randTextureTiles", 4.0);
  60081. }
  60082. effect.setFloat("totalStrength", _this.totalStrength);
  60083. effect.setFloat("radius", _this.radius);
  60084. effect.setFloat("area", _this.area);
  60085. effect.setFloat("fallOff", _this.fallOff);
  60086. effect.setFloat("base", _this.base);
  60087. effect.setTexture("textureSampler", _this._depthTexture);
  60088. effect.setTexture("randomSampler", _this._randomTexture);
  60089. };
  60090. };
  60091. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60092. var _this = this;
  60093. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60094. this._ssaoCombinePostProcess.onApply = function (effect) {
  60095. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60096. };
  60097. };
  60098. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60099. var size = 512;
  60100. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60101. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60102. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60103. var context = this._randomTexture.getContext();
  60104. var rand = function (min, max) {
  60105. return Math.random() * (max - min) + min;
  60106. };
  60107. var randVector = BABYLON.Vector3.Zero();
  60108. for (var x = 0; x < size; x++) {
  60109. for (var y = 0; y < size; y++) {
  60110. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60111. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60112. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60113. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60114. context.fillRect(x, y, 1, 1);
  60115. }
  60116. }
  60117. this._randomTexture.update(false);
  60118. };
  60119. __decorate([
  60120. BABYLON.serialize()
  60121. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60122. __decorate([
  60123. BABYLON.serialize()
  60124. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60125. __decorate([
  60126. BABYLON.serialize()
  60127. ], SSAORenderingPipeline.prototype, "area", void 0);
  60128. __decorate([
  60129. BABYLON.serialize()
  60130. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60131. __decorate([
  60132. BABYLON.serialize()
  60133. ], SSAORenderingPipeline.prototype, "base", void 0);
  60134. return SSAORenderingPipeline;
  60135. }(BABYLON.PostProcessRenderPipeline));
  60136. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60137. })(BABYLON || (BABYLON = {}));
  60138. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60139. var BABYLON;
  60140. (function (BABYLON) {
  60141. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60142. __extends(SSAO2RenderingPipeline, _super);
  60143. /**
  60144. * @constructor
  60145. * @param {string} name - The rendering pipeline name
  60146. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60147. * @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 }
  60148. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60149. */
  60150. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60151. var _this = _super.call(this, scene.getEngine(), name) || this;
  60152. // Members
  60153. /**
  60154. * The PassPostProcess id in the pipeline that contains the original scene color
  60155. * @type {string}
  60156. */
  60157. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60158. /**
  60159. * The SSAO PostProcess id in the pipeline
  60160. * @type {string}
  60161. */
  60162. _this.SSAORenderEffect = "SSAORenderEffect";
  60163. /**
  60164. * The horizontal blur PostProcess id in the pipeline
  60165. * @type {string}
  60166. */
  60167. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60168. /**
  60169. * The vertical blur PostProcess id in the pipeline
  60170. * @type {string}
  60171. */
  60172. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60173. /**
  60174. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60175. * @type {string}
  60176. */
  60177. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60178. /**
  60179. * The output strength of the SSAO post-process. Default value is 1.0.
  60180. * @type {number}
  60181. */
  60182. _this.totalStrength = 1.0;
  60183. /**
  60184. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60185. * @type {number}
  60186. */
  60187. _this.maxZ = 100.0;
  60188. /**
  60189. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60190. * @type {number}
  60191. */
  60192. _this.minZAspect = 0.2;
  60193. /**
  60194. * Number of samples used for the SSAO calculations. Default value is 8
  60195. * @type {number}
  60196. */
  60197. _this._samples = 8;
  60198. /**
  60199. * Are we using bilateral blur ?
  60200. * @type {boolean}
  60201. */
  60202. _this._expensiveBlur = true;
  60203. /**
  60204. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60205. * @type {number}
  60206. */
  60207. _this.radius = 2.0;
  60208. /**
  60209. * The base color of the SSAO post-process
  60210. * The final result is "base + ssao" between [0, 1]
  60211. * @type {number}
  60212. */
  60213. _this.base = 0.1;
  60214. _this._firstUpdate = true;
  60215. _this._scene = scene;
  60216. if (!_this.isSupported) {
  60217. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60218. return _this;
  60219. }
  60220. var ssaoRatio = ratio.ssaoRatio || ratio;
  60221. var blurRatio = ratio.blurRatio || ratio;
  60222. // Set up assets
  60223. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60224. _this._createRandomTexture();
  60225. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60226. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60227. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60228. _this._createSSAOPostProcess(1.0);
  60229. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60230. _this._createSSAOCombinePostProcess(blurRatio);
  60231. // Set up pipeline
  60232. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60233. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60234. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60236. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60237. // Finish
  60238. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60239. if (cameras)
  60240. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60241. return _this;
  60242. }
  60243. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60244. get: function () {
  60245. return this._samples;
  60246. },
  60247. set: function (n) {
  60248. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60249. this._samples = n;
  60250. this._sampleSphere = this._generateHemisphere();
  60251. this._firstUpdate = true;
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60257. get: function () {
  60258. return this._expensiveBlur;
  60259. },
  60260. set: function (b) {
  60261. 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"]);
  60262. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60263. this._expensiveBlur = b;
  60264. this._firstUpdate = true;
  60265. },
  60266. enumerable: true,
  60267. configurable: true
  60268. });
  60269. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60270. /**
  60271. * Support test.
  60272. * @type {boolean}
  60273. */
  60274. get: function () {
  60275. var engine = BABYLON.Engine.LastCreatedEngine;
  60276. if (!engine) {
  60277. return false;
  60278. }
  60279. return engine.getCaps().drawBuffersExtension;
  60280. },
  60281. enumerable: true,
  60282. configurable: true
  60283. });
  60284. // Public Methods
  60285. /**
  60286. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60287. */
  60288. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60289. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60290. for (var i = 0; i < this._scene.cameras.length; i++) {
  60291. var camera = this._scene.cameras[i];
  60292. this._originalColorPostProcess.dispose(camera);
  60293. this._ssaoPostProcess.dispose(camera);
  60294. this._blurHPostProcess.dispose(camera);
  60295. this._blurVPostProcess.dispose(camera);
  60296. this._ssaoCombinePostProcess.dispose(camera);
  60297. }
  60298. this._randomTexture.dispose();
  60299. if (disableGeometryBufferRenderer)
  60300. this._scene.disableGeometryBufferRenderer();
  60301. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60302. _super.prototype.dispose.call(this);
  60303. };
  60304. // Private Methods
  60305. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60306. var _this = this;
  60307. this._samplerOffsets = [];
  60308. var expensive = this.expensiveBlur;
  60309. for (var i = -8; i < 8; i++) {
  60310. this._samplerOffsets.push(i * 2 + 0.5);
  60311. }
  60312. 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");
  60313. this._blurHPostProcess.onApply = function (effect) {
  60314. if (!_this._scene.activeCamera) {
  60315. return;
  60316. }
  60317. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60318. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60319. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60320. effect.setFloat("radius", _this.radius);
  60321. effect.setTexture("depthSampler", _this._depthTexture);
  60322. if (_this._firstUpdate) {
  60323. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60324. }
  60325. };
  60326. 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");
  60327. this._blurVPostProcess.onApply = function (effect) {
  60328. if (!_this._scene.activeCamera) {
  60329. return;
  60330. }
  60331. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60332. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60333. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60334. effect.setFloat("radius", _this.radius);
  60335. effect.setTexture("depthSampler", _this._depthTexture);
  60336. if (_this._firstUpdate) {
  60337. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60338. _this._firstUpdate = false;
  60339. }
  60340. };
  60341. };
  60342. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60343. this._firstUpdate = true;
  60344. _super.prototype._rebuild.call(this);
  60345. };
  60346. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60347. var numSamples = this.samples;
  60348. var result = [];
  60349. var vector, scale;
  60350. var rand = function (min, max) {
  60351. return Math.random() * (max - min) + min;
  60352. };
  60353. var i = 0;
  60354. while (i < numSamples) {
  60355. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60356. vector.normalize();
  60357. scale = i / numSamples;
  60358. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60359. vector.scaleInPlace(scale);
  60360. result.push(vector.x, vector.y, vector.z);
  60361. i++;
  60362. }
  60363. return result;
  60364. };
  60365. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60366. var _this = this;
  60367. var numSamples = this.samples;
  60368. this._sampleSphere = this._generateHemisphere();
  60369. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60370. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60371. "base", "range", "projection", "near", "far", "texelSize",
  60372. "xViewport", "yViewport", "maxZ", "minZAspect"
  60373. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60374. this._ssaoPostProcess.onApply = function (effect) {
  60375. if (_this._firstUpdate) {
  60376. effect.setArray3("sampleSphere", _this._sampleSphere);
  60377. effect.setFloat("randTextureTiles", 4.0);
  60378. }
  60379. if (!_this._scene.activeCamera) {
  60380. return;
  60381. }
  60382. effect.setFloat("samplesFactor", 1 / _this.samples);
  60383. effect.setFloat("totalStrength", _this.totalStrength);
  60384. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60385. effect.setFloat("radius", _this.radius);
  60386. effect.setFloat("maxZ", _this.maxZ);
  60387. effect.setFloat("minZAspect", _this.minZAspect);
  60388. effect.setFloat("base", _this.base);
  60389. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60390. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60391. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60392. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60393. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60394. effect.setTexture("textureSampler", _this._depthTexture);
  60395. effect.setTexture("normalSampler", _this._normalTexture);
  60396. effect.setTexture("randomSampler", _this._randomTexture);
  60397. };
  60398. };
  60399. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60400. var _this = this;
  60401. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60402. this._ssaoCombinePostProcess.onApply = function (effect) {
  60403. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60404. };
  60405. };
  60406. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60407. var size = 512;
  60408. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60409. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60410. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60411. var context = this._randomTexture.getContext();
  60412. var rand = function (min, max) {
  60413. return Math.random() * (max - min) + min;
  60414. };
  60415. var randVector = BABYLON.Vector3.Zero();
  60416. for (var x = 0; x < size; x++) {
  60417. for (var y = 0; y < size; y++) {
  60418. randVector.x = rand(0.0, 1.0);
  60419. randVector.y = rand(0.0, 1.0);
  60420. randVector.z = 0.0;
  60421. randVector.normalize();
  60422. randVector.scaleInPlace(255);
  60423. randVector.x = Math.floor(randVector.x);
  60424. randVector.y = Math.floor(randVector.y);
  60425. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60426. context.fillRect(x, y, 1, 1);
  60427. }
  60428. }
  60429. this._randomTexture.update(false);
  60430. };
  60431. __decorate([
  60432. BABYLON.serialize()
  60433. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60434. __decorate([
  60435. BABYLON.serialize()
  60436. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60437. __decorate([
  60438. BABYLON.serialize()
  60439. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60440. __decorate([
  60441. BABYLON.serialize("samples")
  60442. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60443. __decorate([
  60444. BABYLON.serialize("expensiveBlur")
  60445. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60446. __decorate([
  60447. BABYLON.serialize()
  60448. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60449. __decorate([
  60450. BABYLON.serialize()
  60451. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60452. return SSAO2RenderingPipeline;
  60453. }(BABYLON.PostProcessRenderPipeline));
  60454. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60455. })(BABYLON || (BABYLON = {}));
  60456. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60457. // BABYLON.JS Chromatic Aberration GLSL Shader
  60458. // Author: Olivier Guyot
  60459. // Separates very slightly R, G and B colors on the edges of the screen
  60460. // Inspired by Francois Tarlier & Martins Upitis
  60461. var BABYLON;
  60462. (function (BABYLON) {
  60463. var LensRenderingPipeline = /** @class */ (function (_super) {
  60464. __extends(LensRenderingPipeline, _super);
  60465. /**
  60466. * @constructor
  60467. *
  60468. * Effect parameters are as follow:
  60469. * {
  60470. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60471. * edge_blur: number; // from 0 to x (1 for realism)
  60472. * distortion: number; // from 0 to x (1 for realism)
  60473. * grain_amount: number; // from 0 to 1
  60474. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60475. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60476. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60477. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60478. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60479. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60480. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60481. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60482. * }
  60483. * Note: if an effect parameter is unset, effect is disabled
  60484. *
  60485. * @param {string} name - The rendering pipeline name
  60486. * @param {object} parameters - An object containing all parameters (see above)
  60487. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60488. * @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)
  60489. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60490. */
  60491. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60492. if (ratio === void 0) { ratio = 1.0; }
  60493. var _this = _super.call(this, scene.getEngine(), name) || this;
  60494. // Lens effects can be of the following:
  60495. // - chromatic aberration (slight shift of RGB colors)
  60496. // - blur on the edge of the lens
  60497. // - lens distortion
  60498. // - depth-of-field blur & highlights enhancing
  60499. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60500. // - grain effect (noise or custom texture)
  60501. // Two additional texture samplers are needed:
  60502. // - depth map (for depth-of-field)
  60503. // - grain texture
  60504. /**
  60505. * The chromatic aberration PostProcess id in the pipeline
  60506. * @type {string}
  60507. */
  60508. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60509. /**
  60510. * The highlights enhancing PostProcess id in the pipeline
  60511. * @type {string}
  60512. */
  60513. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60514. /**
  60515. * The depth-of-field PostProcess id in the pipeline
  60516. * @type {string}
  60517. */
  60518. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60519. _this._scene = scene;
  60520. // Fetch texture samplers
  60521. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60522. if (parameters.grain_texture) {
  60523. _this._grainTexture = parameters.grain_texture;
  60524. }
  60525. else {
  60526. _this._createGrainTexture();
  60527. }
  60528. // save parameters
  60529. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60530. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60531. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60532. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60533. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60534. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60535. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60536. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60537. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60538. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60539. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60540. // Create effects
  60541. _this._createChromaticAberrationPostProcess(ratio);
  60542. _this._createHighlightsPostProcess(ratio);
  60543. _this._createDepthOfFieldPostProcess(ratio / 4);
  60544. // Set up pipeline
  60545. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60546. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60547. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60548. if (_this._highlightsGain === -1) {
  60549. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60550. }
  60551. // Finish
  60552. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60553. if (cameras) {
  60554. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60555. }
  60556. return _this;
  60557. }
  60558. // public methods (self explanatory)
  60559. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60560. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60561. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60562. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60563. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60564. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60565. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60566. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60567. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60568. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60569. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60570. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60571. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60572. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60573. };
  60574. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60575. this._highlightsPostProcess.updateEffect();
  60576. };
  60577. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60578. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60579. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60580. this._highlightsGain = amount;
  60581. };
  60582. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60583. if (this._highlightsGain === -1) {
  60584. this._highlightsGain = 1.0;
  60585. }
  60586. this._highlightsThreshold = amount;
  60587. };
  60588. LensRenderingPipeline.prototype.disableHighlights = function () {
  60589. this._highlightsGain = -1;
  60590. };
  60591. /**
  60592. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60593. */
  60594. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60595. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60596. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60597. this._chromaticAberrationPostProcess = null;
  60598. this._highlightsPostProcess = null;
  60599. this._depthOfFieldPostProcess = null;
  60600. this._grainTexture.dispose();
  60601. if (disableDepthRender)
  60602. this._scene.disableDepthRenderer();
  60603. };
  60604. // colors shifting and distortion
  60605. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60606. var _this = this;
  60607. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60608. [], // samplers
  60609. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60610. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60611. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60612. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60613. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60614. };
  60615. };
  60616. // highlights enhancing
  60617. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60618. var _this = this;
  60619. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60620. [], // samplers
  60621. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60622. this._highlightsPostProcess.onApply = function (effect) {
  60623. effect.setFloat('gain', _this._highlightsGain);
  60624. effect.setFloat('threshold', _this._highlightsThreshold);
  60625. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60626. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60627. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60628. };
  60629. };
  60630. // colors shifting and distortion
  60631. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60632. var _this = this;
  60633. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60634. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60635. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60636. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60637. this._depthOfFieldPostProcess.onApply = function (effect) {
  60638. effect.setTexture("depthSampler", _this._depthTexture);
  60639. effect.setTexture("grainSampler", _this._grainTexture);
  60640. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60641. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60642. effect.setFloat('grain_amount', _this._grainAmount);
  60643. effect.setBool('blur_noise', _this._blurNoise);
  60644. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60645. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60646. effect.setFloat('distortion', _this._distortion);
  60647. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60648. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60649. effect.setFloat('aperture', _this._dofAperture);
  60650. effect.setFloat('darken', _this._dofDarken);
  60651. effect.setFloat('edge_blur', _this._edgeBlur);
  60652. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60653. if (_this._scene.activeCamera) {
  60654. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60655. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60656. }
  60657. };
  60658. };
  60659. // creates a black and white random noise texture, 512x512
  60660. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60661. var size = 512;
  60662. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60663. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60664. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60665. var context = this._grainTexture.getContext();
  60666. var rand = function (min, max) {
  60667. return Math.random() * (max - min) + min;
  60668. };
  60669. var value;
  60670. for (var x = 0; x < size; x++) {
  60671. for (var y = 0; y < size; y++) {
  60672. value = Math.floor(rand(0.42, 0.58) * 255);
  60673. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60674. context.fillRect(x, y, 1, 1);
  60675. }
  60676. }
  60677. this._grainTexture.update(false);
  60678. };
  60679. return LensRenderingPipeline;
  60680. }(BABYLON.PostProcessRenderPipeline));
  60681. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60682. })(BABYLON || (BABYLON = {}));
  60683. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60684. var BABYLON;
  60685. (function (BABYLON) {
  60686. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60687. __extends(StandardRenderingPipeline, _super);
  60688. /**
  60689. * @constructor
  60690. * @param {string} name - The rendering pipeline name
  60691. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60692. * @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)
  60693. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60694. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60695. */
  60696. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60697. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60698. var _this = _super.call(this, scene.getEngine(), name) || this;
  60699. _this.downSampleX4PostProcess = null;
  60700. _this.brightPassPostProcess = null;
  60701. _this.blurHPostProcesses = [];
  60702. _this.blurVPostProcesses = [];
  60703. _this.textureAdderPostProcess = null;
  60704. _this.volumetricLightPostProcess = null;
  60705. _this.volumetricLightSmoothXPostProcess = null;
  60706. _this.volumetricLightSmoothYPostProcess = null;
  60707. _this.volumetricLightMergePostProces = null;
  60708. _this.volumetricLightFinalPostProcess = null;
  60709. _this.luminancePostProcess = null;
  60710. _this.luminanceDownSamplePostProcesses = [];
  60711. _this.hdrPostProcess = null;
  60712. _this.textureAdderFinalPostProcess = null;
  60713. _this.lensFlareFinalPostProcess = null;
  60714. _this.hdrFinalPostProcess = null;
  60715. _this.lensFlarePostProcess = null;
  60716. _this.lensFlareComposePostProcess = null;
  60717. _this.motionBlurPostProcess = null;
  60718. _this.depthOfFieldPostProcess = null;
  60719. // Values
  60720. _this.brightThreshold = 1.0;
  60721. _this.blurWidth = 512.0;
  60722. _this.horizontalBlur = false;
  60723. _this.exposure = 1.0;
  60724. _this.lensTexture = null;
  60725. _this.volumetricLightCoefficient = 0.2;
  60726. _this.volumetricLightPower = 4.0;
  60727. _this.volumetricLightBlurScale = 64.0;
  60728. _this.sourceLight = null;
  60729. _this.hdrMinimumLuminance = 1.0;
  60730. _this.hdrDecreaseRate = 0.5;
  60731. _this.hdrIncreaseRate = 0.5;
  60732. _this.lensColorTexture = null;
  60733. _this.lensFlareStrength = 20.0;
  60734. _this.lensFlareGhostDispersal = 1.4;
  60735. _this.lensFlareHaloWidth = 0.7;
  60736. _this.lensFlareDistortionStrength = 16.0;
  60737. _this.lensStarTexture = null;
  60738. _this.lensFlareDirtTexture = null;
  60739. _this.depthOfFieldDistance = 10.0;
  60740. _this.depthOfFieldBlurWidth = 64.0;
  60741. _this.motionStrength = 1.0;
  60742. // IAnimatable
  60743. _this.animations = [];
  60744. _this._currentDepthOfFieldSource = null;
  60745. _this._hdrCurrentLuminance = 1.0;
  60746. // Getters and setters
  60747. _this._bloomEnabled = true;
  60748. _this._depthOfFieldEnabled = false;
  60749. _this._vlsEnabled = false;
  60750. _this._lensFlareEnabled = false;
  60751. _this._hdrEnabled = false;
  60752. _this._motionBlurEnabled = false;
  60753. _this._motionBlurSamples = 64.0;
  60754. _this._volumetricLightStepsCount = 50.0;
  60755. _this._cameras = cameras || [];
  60756. // Initialize
  60757. _this._scene = scene;
  60758. _this._basePostProcess = originalPostProcess;
  60759. _this._ratio = ratio;
  60760. // Misc
  60761. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60762. // Finish
  60763. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60764. _this._buildPipeline();
  60765. return _this;
  60766. }
  60767. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60768. get: function () {
  60769. return this._bloomEnabled;
  60770. },
  60771. set: function (enabled) {
  60772. if (this._bloomEnabled === enabled) {
  60773. return;
  60774. }
  60775. this._bloomEnabled = enabled;
  60776. this._buildPipeline();
  60777. },
  60778. enumerable: true,
  60779. configurable: true
  60780. });
  60781. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60782. get: function () {
  60783. return this._depthOfFieldEnabled;
  60784. },
  60785. set: function (enabled) {
  60786. if (this._depthOfFieldEnabled === enabled) {
  60787. return;
  60788. }
  60789. this._depthOfFieldEnabled = enabled;
  60790. this._buildPipeline();
  60791. },
  60792. enumerable: true,
  60793. configurable: true
  60794. });
  60795. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60796. get: function () {
  60797. return this._lensFlareEnabled;
  60798. },
  60799. set: function (enabled) {
  60800. if (this._lensFlareEnabled === enabled) {
  60801. return;
  60802. }
  60803. this._lensFlareEnabled = enabled;
  60804. this._buildPipeline();
  60805. },
  60806. enumerable: true,
  60807. configurable: true
  60808. });
  60809. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60810. get: function () {
  60811. return this._hdrEnabled;
  60812. },
  60813. set: function (enabled) {
  60814. if (this._hdrEnabled === enabled) {
  60815. return;
  60816. }
  60817. this._hdrEnabled = enabled;
  60818. this._buildPipeline();
  60819. },
  60820. enumerable: true,
  60821. configurable: true
  60822. });
  60823. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60824. get: function () {
  60825. return this._vlsEnabled;
  60826. },
  60827. set: function (enabled) {
  60828. if (this._vlsEnabled === enabled) {
  60829. return;
  60830. }
  60831. if (enabled) {
  60832. var geometry = this._scene.enableGeometryBufferRenderer();
  60833. if (!geometry) {
  60834. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60835. return;
  60836. }
  60837. }
  60838. this._vlsEnabled = enabled;
  60839. this._buildPipeline();
  60840. },
  60841. enumerable: true,
  60842. configurable: true
  60843. });
  60844. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60845. get: function () {
  60846. return this._motionBlurEnabled;
  60847. },
  60848. set: function (enabled) {
  60849. if (this._motionBlurEnabled === enabled) {
  60850. return;
  60851. }
  60852. this._motionBlurEnabled = enabled;
  60853. this._buildPipeline();
  60854. },
  60855. enumerable: true,
  60856. configurable: true
  60857. });
  60858. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60859. get: function () {
  60860. return this._volumetricLightStepsCount;
  60861. },
  60862. set: function (count) {
  60863. if (this.volumetricLightPostProcess) {
  60864. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60865. }
  60866. this._volumetricLightStepsCount = count;
  60867. },
  60868. enumerable: true,
  60869. configurable: true
  60870. });
  60871. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60872. get: function () {
  60873. return this._motionBlurSamples;
  60874. },
  60875. set: function (samples) {
  60876. if (this.motionBlurPostProcess) {
  60877. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60878. }
  60879. this._motionBlurSamples = samples;
  60880. },
  60881. enumerable: true,
  60882. configurable: true
  60883. });
  60884. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60885. var _this = this;
  60886. var ratio = this._ratio;
  60887. var scene = this._scene;
  60888. this._disposePostProcesses();
  60889. this._reset();
  60890. // Create pass post-process
  60891. if (!this._basePostProcess) {
  60892. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60893. this.originalPostProcess.onApply = function (effect) {
  60894. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60895. };
  60896. }
  60897. else {
  60898. this.originalPostProcess = this._basePostProcess;
  60899. }
  60900. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60901. this._currentDepthOfFieldSource = this.originalPostProcess;
  60902. if (this._vlsEnabled) {
  60903. // Create volumetric light
  60904. this._createVolumetricLightPostProcess(scene, ratio);
  60905. // Create volumetric light final post-process
  60906. 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);
  60907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60908. }
  60909. if (this._bloomEnabled) {
  60910. // Create down sample X4 post-process
  60911. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60912. // Create bright pass post-process
  60913. this._createBrightPassPostProcess(scene, ratio / 2);
  60914. // Create gaussian blur post-processes (down sampling blurs)
  60915. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60916. // Create texture adder post-process
  60917. this._createTextureAdderPostProcess(scene, ratio);
  60918. // Create depth-of-field source post-process
  60919. 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);
  60920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60921. }
  60922. if (this._lensFlareEnabled) {
  60923. // Create lens flare post-process
  60924. this._createLensFlarePostProcess(scene, ratio);
  60925. // Create depth-of-field source post-process post lens-flare and disable it now
  60926. 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);
  60927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60928. }
  60929. if (this._hdrEnabled) {
  60930. // Create luminance
  60931. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60932. // Create HDR
  60933. this._createHdrPostProcess(scene, ratio);
  60934. // Create depth-of-field source post-process post hdr and disable it now
  60935. 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);
  60936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60937. }
  60938. if (this._depthOfFieldEnabled) {
  60939. // Create gaussian blur used by depth-of-field
  60940. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60941. // Create depth-of-field post-process
  60942. this._createDepthOfFieldPostProcess(scene, ratio);
  60943. }
  60944. if (this._motionBlurEnabled) {
  60945. // Create motion blur post-process
  60946. this._createMotionBlurPostProcess(scene, ratio);
  60947. }
  60948. if (this._cameras !== null) {
  60949. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60950. }
  60951. };
  60952. // Down Sample X4 Post-Processs
  60953. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60954. var _this = this;
  60955. var downSampleX4Offsets = new Array(32);
  60956. 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);
  60957. this.downSampleX4PostProcess.onApply = function (effect) {
  60958. var id = 0;
  60959. var width = _this.downSampleX4PostProcess.width;
  60960. var height = _this.downSampleX4PostProcess.height;
  60961. for (var i = -2; i < 2; i++) {
  60962. for (var j = -2; j < 2; j++) {
  60963. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60964. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  60965. id += 2;
  60966. }
  60967. }
  60968. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60969. };
  60970. // Add to pipeline
  60971. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60972. };
  60973. // Brightpass Post-Process
  60974. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60975. var _this = this;
  60976. var brightOffsets = new Array(8);
  60977. 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);
  60978. this.brightPassPostProcess.onApply = function (effect) {
  60979. var sU = (1.0 / _this.brightPassPostProcess.width);
  60980. var sV = (1.0 / _this.brightPassPostProcess.height);
  60981. brightOffsets[0] = -0.5 * sU;
  60982. brightOffsets[1] = 0.5 * sV;
  60983. brightOffsets[2] = 0.5 * sU;
  60984. brightOffsets[3] = 0.5 * sV;
  60985. brightOffsets[4] = -0.5 * sU;
  60986. brightOffsets[5] = -0.5 * sV;
  60987. brightOffsets[6] = 0.5 * sU;
  60988. brightOffsets[7] = -0.5 * sV;
  60989. effect.setArray2("dsOffsets", brightOffsets);
  60990. effect.setFloat("brightThreshold", _this.brightThreshold);
  60991. };
  60992. // Add to pipeline
  60993. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60994. };
  60995. // Create blur H&V post-processes
  60996. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  60997. var _this = this;
  60998. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  60999. var engine = scene.getEngine();
  61000. 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);
  61001. 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);
  61002. blurX.onActivateObservable.add(function () {
  61003. var dw = blurX.width / engine.getRenderWidth();
  61004. blurX.kernel = _this[blurWidthKey] * dw;
  61005. });
  61006. blurY.onActivateObservable.add(function () {
  61007. var dw = blurY.height / engine.getRenderHeight();
  61008. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61009. });
  61010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61012. this.blurHPostProcesses.push(blurX);
  61013. this.blurVPostProcesses.push(blurY);
  61014. };
  61015. // Create texture adder post-process
  61016. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61017. var _this = this;
  61018. 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);
  61019. this.textureAdderPostProcess.onApply = function (effect) {
  61020. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61021. effect.setTexture("lensSampler", _this.lensTexture);
  61022. effect.setFloat("exposure", _this.exposure);
  61023. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61024. };
  61025. // Add to pipeline
  61026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61027. };
  61028. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61029. var _this = this;
  61030. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61031. geometryRenderer.enablePosition = true;
  61032. var geometry = geometryRenderer.getGBuffer();
  61033. // Base post-process
  61034. 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));
  61035. var depthValues = BABYLON.Vector2.Zero();
  61036. this.volumetricLightPostProcess.onApply = function (effect) {
  61037. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61038. var generator = _this.sourceLight.getShadowGenerator();
  61039. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61040. effect.setTexture("positionSampler", geometry.textures[2]);
  61041. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61042. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61043. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61044. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61045. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61046. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61047. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61048. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61049. effect.setVector2("depthValues", depthValues);
  61050. }
  61051. };
  61052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61053. // Smooth
  61054. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61055. // Merge
  61056. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61057. this.volumetricLightMergePostProces.onApply = function (effect) {
  61058. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61059. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61060. };
  61061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61062. };
  61063. // Create luminance
  61064. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61065. var _this = this;
  61066. // Create luminance
  61067. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61068. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61069. var offsets = [];
  61070. this.luminancePostProcess.onApply = function (effect) {
  61071. var sU = (1.0 / _this.luminancePostProcess.width);
  61072. var sV = (1.0 / _this.luminancePostProcess.height);
  61073. offsets[0] = -0.5 * sU;
  61074. offsets[1] = 0.5 * sV;
  61075. offsets[2] = 0.5 * sU;
  61076. offsets[3] = 0.5 * sV;
  61077. offsets[4] = -0.5 * sU;
  61078. offsets[5] = -0.5 * sV;
  61079. offsets[6] = 0.5 * sU;
  61080. offsets[7] = -0.5 * sV;
  61081. effect.setArray2("lumOffsets", offsets);
  61082. };
  61083. // Add to pipeline
  61084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61085. // Create down sample luminance
  61086. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61087. var size = Math.pow(3, i);
  61088. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61089. if (i === 0) {
  61090. defines += "#define FINAL_DOWN_SAMPLER";
  61091. }
  61092. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61093. this.luminanceDownSamplePostProcesses.push(postProcess);
  61094. }
  61095. // Create callbacks and add effects
  61096. var lastLuminance = this.luminancePostProcess;
  61097. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61098. var downSampleOffsets = new Array(18);
  61099. pp.onApply = function (effect) {
  61100. if (!lastLuminance) {
  61101. return;
  61102. }
  61103. var id = 0;
  61104. for (var x = -1; x < 2; x++) {
  61105. for (var y = -1; y < 2; y++) {
  61106. downSampleOffsets[id] = x / lastLuminance.width;
  61107. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61108. id += 2;
  61109. }
  61110. }
  61111. effect.setArray2("dsOffsets", downSampleOffsets);
  61112. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61113. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61114. lastLuminance = _this.luminancePostProcess;
  61115. }
  61116. else {
  61117. lastLuminance = pp;
  61118. }
  61119. };
  61120. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61121. pp.onAfterRender = function (effect) {
  61122. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61123. 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);
  61124. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61125. };
  61126. }
  61127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61128. });
  61129. };
  61130. // Create HDR post-process
  61131. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61132. var _this = this;
  61133. 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);
  61134. var outputLiminance = 1;
  61135. var time = 0;
  61136. var lastTime = 0;
  61137. this.hdrPostProcess.onApply = function (effect) {
  61138. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61139. time += scene.getEngine().getDeltaTime();
  61140. if (outputLiminance < 0) {
  61141. outputLiminance = _this._hdrCurrentLuminance;
  61142. }
  61143. else {
  61144. var dt = (lastTime - time) / 1000.0;
  61145. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61146. outputLiminance += _this.hdrDecreaseRate * dt;
  61147. }
  61148. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61149. outputLiminance -= _this.hdrIncreaseRate * dt;
  61150. }
  61151. else {
  61152. outputLiminance = _this._hdrCurrentLuminance;
  61153. }
  61154. }
  61155. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61156. effect.setFloat("averageLuminance", outputLiminance);
  61157. lastTime = time;
  61158. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61159. };
  61160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61161. };
  61162. // Create lens flare post-process
  61163. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61164. var _this = this;
  61165. 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);
  61166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61167. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61168. 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);
  61169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61170. var resolution = new BABYLON.Vector2(0, 0);
  61171. // Lens flare
  61172. this.lensFlarePostProcess.onApply = function (effect) {
  61173. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61174. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61175. effect.setFloat("strength", _this.lensFlareStrength);
  61176. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61177. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61178. // Shift
  61179. resolution.x = _this.lensFlarePostProcess.width;
  61180. resolution.y = _this.lensFlarePostProcess.height;
  61181. effect.setVector2("resolution", resolution);
  61182. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61183. };
  61184. // Compose
  61185. 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);
  61186. 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);
  61187. this.lensFlareComposePostProcess.onApply = function (effect) {
  61188. if (!_this._scene.activeCamera) {
  61189. return;
  61190. }
  61191. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61192. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61193. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61194. // Lens start rotation matrix
  61195. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61196. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61197. 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));
  61198. camRot *= 4.0;
  61199. 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);
  61200. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61201. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61202. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61203. };
  61204. };
  61205. // Create depth-of-field post-process
  61206. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61207. var _this = this;
  61208. 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);
  61209. this.depthOfFieldPostProcess.onApply = function (effect) {
  61210. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61211. effect.setTexture("depthSampler", _this._getDepthTexture());
  61212. effect.setFloat("distance", _this.depthOfFieldDistance);
  61213. };
  61214. // Add to pipeline
  61215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61216. };
  61217. // Create motion blur post-process
  61218. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61219. var _this = this;
  61220. 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);
  61221. var motionScale = 0;
  61222. var prevViewProjection = BABYLON.Matrix.Identity();
  61223. var invViewProjection = BABYLON.Matrix.Identity();
  61224. var viewProjection = BABYLON.Matrix.Identity();
  61225. var screenSize = BABYLON.Vector2.Zero();
  61226. this.motionBlurPostProcess.onApply = function (effect) {
  61227. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61228. viewProjection.invertToRef(invViewProjection);
  61229. effect.setMatrix("inverseViewProjection", invViewProjection);
  61230. effect.setMatrix("prevViewProjection", prevViewProjection);
  61231. prevViewProjection = viewProjection;
  61232. screenSize.x = _this.motionBlurPostProcess.width;
  61233. screenSize.y = _this.motionBlurPostProcess.height;
  61234. effect.setVector2("screenSize", screenSize);
  61235. motionScale = scene.getEngine().getFps() / 60.0;
  61236. effect.setFloat("motionScale", motionScale);
  61237. effect.setFloat("motionStrength", _this.motionStrength);
  61238. effect.setTexture("depthSampler", _this._getDepthTexture());
  61239. };
  61240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61241. };
  61242. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61243. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61244. var renderer = this._scene.enableGeometryBufferRenderer();
  61245. return renderer.getGBuffer().textures[0];
  61246. }
  61247. return this._scene.enableDepthRenderer().getDepthMap();
  61248. };
  61249. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61250. for (var i = 0; i < this._cameras.length; i++) {
  61251. var camera = this._cameras[i];
  61252. if (this.originalPostProcess) {
  61253. this.originalPostProcess.dispose(camera);
  61254. }
  61255. if (this.downSampleX4PostProcess) {
  61256. this.downSampleX4PostProcess.dispose(camera);
  61257. }
  61258. if (this.brightPassPostProcess) {
  61259. this.brightPassPostProcess.dispose(camera);
  61260. }
  61261. if (this.textureAdderPostProcess) {
  61262. this.textureAdderPostProcess.dispose(camera);
  61263. }
  61264. if (this.textureAdderFinalPostProcess) {
  61265. this.textureAdderFinalPostProcess.dispose(camera);
  61266. }
  61267. if (this.volumetricLightPostProcess) {
  61268. this.volumetricLightPostProcess.dispose(camera);
  61269. }
  61270. if (this.volumetricLightSmoothXPostProcess) {
  61271. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61272. }
  61273. if (this.volumetricLightSmoothYPostProcess) {
  61274. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61275. }
  61276. if (this.volumetricLightMergePostProces) {
  61277. this.volumetricLightMergePostProces.dispose(camera);
  61278. }
  61279. if (this.volumetricLightFinalPostProcess) {
  61280. this.volumetricLightFinalPostProcess.dispose(camera);
  61281. }
  61282. if (this.lensFlarePostProcess) {
  61283. this.lensFlarePostProcess.dispose(camera);
  61284. }
  61285. if (this.lensFlareComposePostProcess) {
  61286. this.lensFlareComposePostProcess.dispose(camera);
  61287. }
  61288. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61289. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61290. }
  61291. if (this.luminancePostProcess) {
  61292. this.luminancePostProcess.dispose(camera);
  61293. }
  61294. if (this.hdrPostProcess) {
  61295. this.hdrPostProcess.dispose(camera);
  61296. }
  61297. if (this.hdrFinalPostProcess) {
  61298. this.hdrFinalPostProcess.dispose(camera);
  61299. }
  61300. if (this.depthOfFieldPostProcess) {
  61301. this.depthOfFieldPostProcess.dispose(camera);
  61302. }
  61303. if (this.motionBlurPostProcess) {
  61304. this.motionBlurPostProcess.dispose(camera);
  61305. }
  61306. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61307. this.blurHPostProcesses[j].dispose(camera);
  61308. }
  61309. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61310. this.blurVPostProcesses[j].dispose(camera);
  61311. }
  61312. }
  61313. this.originalPostProcess = null;
  61314. this.downSampleX4PostProcess = null;
  61315. this.brightPassPostProcess = null;
  61316. this.textureAdderPostProcess = null;
  61317. this.textureAdderFinalPostProcess = null;
  61318. this.volumetricLightPostProcess = null;
  61319. this.volumetricLightSmoothXPostProcess = null;
  61320. this.volumetricLightSmoothYPostProcess = null;
  61321. this.volumetricLightMergePostProces = null;
  61322. this.volumetricLightFinalPostProcess = null;
  61323. this.lensFlarePostProcess = null;
  61324. this.lensFlareComposePostProcess = null;
  61325. this.luminancePostProcess = null;
  61326. this.hdrPostProcess = null;
  61327. this.hdrFinalPostProcess = null;
  61328. this.depthOfFieldPostProcess = null;
  61329. this.motionBlurPostProcess = null;
  61330. this.luminanceDownSamplePostProcesses = [];
  61331. this.blurHPostProcesses = [];
  61332. this.blurVPostProcesses = [];
  61333. };
  61334. // Dispose
  61335. StandardRenderingPipeline.prototype.dispose = function () {
  61336. this._disposePostProcesses();
  61337. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61338. _super.prototype.dispose.call(this);
  61339. };
  61340. // Serialize rendering pipeline
  61341. StandardRenderingPipeline.prototype.serialize = function () {
  61342. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61343. serializationObject.customType = "StandardRenderingPipeline";
  61344. return serializationObject;
  61345. };
  61346. /**
  61347. * Static members
  61348. */
  61349. // Parse serialized pipeline
  61350. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61351. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61352. };
  61353. // Luminance steps
  61354. StandardRenderingPipeline.LuminanceSteps = 6;
  61355. __decorate([
  61356. BABYLON.serialize()
  61357. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61358. __decorate([
  61359. BABYLON.serialize()
  61360. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61361. __decorate([
  61362. BABYLON.serialize()
  61363. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61364. __decorate([
  61365. BABYLON.serialize()
  61366. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61367. __decorate([
  61368. BABYLON.serializeAsTexture("lensTexture")
  61369. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61370. __decorate([
  61371. BABYLON.serialize()
  61372. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61373. __decorate([
  61374. BABYLON.serialize()
  61375. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61376. __decorate([
  61377. BABYLON.serialize()
  61378. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61379. __decorate([
  61380. BABYLON.serialize()
  61381. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61382. __decorate([
  61383. BABYLON.serialize()
  61384. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61385. __decorate([
  61386. BABYLON.serialize()
  61387. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61388. __decorate([
  61389. BABYLON.serializeAsTexture("lensColorTexture")
  61390. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61391. __decorate([
  61392. BABYLON.serialize()
  61393. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61394. __decorate([
  61395. BABYLON.serialize()
  61396. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61397. __decorate([
  61398. BABYLON.serialize()
  61399. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61400. __decorate([
  61401. BABYLON.serialize()
  61402. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61403. __decorate([
  61404. BABYLON.serializeAsTexture("lensStarTexture")
  61405. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61406. __decorate([
  61407. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61408. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61409. __decorate([
  61410. BABYLON.serialize()
  61411. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61412. __decorate([
  61413. BABYLON.serialize()
  61414. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61415. __decorate([
  61416. BABYLON.serialize()
  61417. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61418. __decorate([
  61419. BABYLON.serialize()
  61420. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61421. __decorate([
  61422. BABYLON.serialize()
  61423. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61424. __decorate([
  61425. BABYLON.serialize()
  61426. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61427. __decorate([
  61428. BABYLON.serialize()
  61429. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61430. __decorate([
  61431. BABYLON.serialize()
  61432. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61433. __decorate([
  61434. BABYLON.serialize()
  61435. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61436. __decorate([
  61437. BABYLON.serialize()
  61438. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61439. __decorate([
  61440. BABYLON.serialize()
  61441. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61442. __decorate([
  61443. BABYLON.serialize()
  61444. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61445. return StandardRenderingPipeline;
  61446. }(BABYLON.PostProcessRenderPipeline));
  61447. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61448. })(BABYLON || (BABYLON = {}));
  61449. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61450. var BABYLON;
  61451. (function (BABYLON) {
  61452. var FxaaPostProcess = /** @class */ (function (_super) {
  61453. __extends(FxaaPostProcess, _super);
  61454. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61455. if (camera === void 0) { camera = null; }
  61456. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61457. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61458. _this.onApplyObservable.add(function (effect) {
  61459. var texelSize = _this.texelSize;
  61460. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61461. });
  61462. return _this;
  61463. }
  61464. return FxaaPostProcess;
  61465. }(BABYLON.PostProcess));
  61466. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61467. })(BABYLON || (BABYLON = {}));
  61468. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61469. var BABYLON;
  61470. (function (BABYLON) {
  61471. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61472. __extends(DefaultRenderingPipeline, _super);
  61473. /**
  61474. * @constructor
  61475. * @param {string} name - The rendering pipeline name
  61476. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61477. * @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)
  61478. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61479. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61480. */
  61481. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61482. if (automaticBuild === void 0) { automaticBuild = true; }
  61483. var _this = _super.call(this, scene.getEngine(), name) || this;
  61484. _this.PassPostProcessId = "PassPostProcessEffect";
  61485. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61486. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61487. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61488. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61489. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61490. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61491. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61492. // IAnimatable
  61493. _this.animations = [];
  61494. // Values
  61495. _this._bloomEnabled = false;
  61496. _this._fxaaEnabled = false;
  61497. _this._imageProcessingEnabled = true;
  61498. _this._bloomScale = 0.6;
  61499. _this._buildAllowed = true;
  61500. /**
  61501. * Specifies the size of the bloom blur kernel, relative to the final output size
  61502. */
  61503. _this.bloomKernel = 64;
  61504. /**
  61505. * Specifies the weight of the bloom in the final rendering
  61506. */
  61507. _this._bloomWeight = 0.15;
  61508. _this._cameras = cameras || [];
  61509. _this._buildAllowed = automaticBuild;
  61510. // Initialize
  61511. _this._scene = scene;
  61512. var caps = _this._scene.getEngine().getCaps();
  61513. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61514. // Misc
  61515. if (_this._hdr) {
  61516. if (caps.textureHalfFloatRender) {
  61517. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61518. }
  61519. else if (caps.textureFloatRender) {
  61520. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61521. }
  61522. }
  61523. else {
  61524. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61525. }
  61526. // Attach
  61527. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61528. _this._buildPipeline();
  61529. return _this;
  61530. }
  61531. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61532. get: function () {
  61533. return this._bloomWeight;
  61534. },
  61535. set: function (value) {
  61536. if (this._bloomWeight === value) {
  61537. return;
  61538. }
  61539. this._bloomWeight = value;
  61540. if (this._hdr && this.copyBack) {
  61541. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61542. }
  61543. },
  61544. enumerable: true,
  61545. configurable: true
  61546. });
  61547. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61548. get: function () {
  61549. return this._bloomScale;
  61550. },
  61551. set: function (value) {
  61552. if (this._bloomScale === value) {
  61553. return;
  61554. }
  61555. this._bloomScale = value;
  61556. this._buildPipeline();
  61557. },
  61558. enumerable: true,
  61559. configurable: true
  61560. });
  61561. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61562. get: function () {
  61563. return this._bloomEnabled;
  61564. },
  61565. set: function (enabled) {
  61566. if (this._bloomEnabled === enabled) {
  61567. return;
  61568. }
  61569. this._bloomEnabled = enabled;
  61570. this._buildPipeline();
  61571. },
  61572. enumerable: true,
  61573. configurable: true
  61574. });
  61575. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61576. get: function () {
  61577. return this._fxaaEnabled;
  61578. },
  61579. set: function (enabled) {
  61580. if (this._fxaaEnabled === enabled) {
  61581. return;
  61582. }
  61583. this._fxaaEnabled = enabled;
  61584. this._buildPipeline();
  61585. },
  61586. enumerable: true,
  61587. configurable: true
  61588. });
  61589. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61590. get: function () {
  61591. return this._imageProcessingEnabled;
  61592. },
  61593. set: function (enabled) {
  61594. if (this._imageProcessingEnabled === enabled) {
  61595. return;
  61596. }
  61597. this._imageProcessingEnabled = enabled;
  61598. this._buildPipeline();
  61599. },
  61600. enumerable: true,
  61601. configurable: true
  61602. });
  61603. /**
  61604. * Force the compilation of the entire pipeline.
  61605. */
  61606. DefaultRenderingPipeline.prototype.prepare = function () {
  61607. var previousState = this._buildAllowed;
  61608. this._buildAllowed = true;
  61609. this._buildPipeline();
  61610. this._buildAllowed = previousState;
  61611. };
  61612. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61613. var _this = this;
  61614. if (!this._buildAllowed) {
  61615. return;
  61616. }
  61617. var engine = this._scene.getEngine();
  61618. this._disposePostProcesses();
  61619. this._reset();
  61620. if (this.bloomEnabled) {
  61621. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61622. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61623. if (!this._hdr) {
  61624. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61625. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61626. this.highlights.autoClear = false;
  61627. this.highlights.alwaysForcePOT = true;
  61628. }
  61629. 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);
  61630. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61631. this.blurX.alwaysForcePOT = true;
  61632. this.blurX.autoClear = false;
  61633. this.blurX.onActivateObservable.add(function () {
  61634. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61635. _this.blurX.kernel = _this.bloomKernel * dw;
  61636. });
  61637. 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);
  61638. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61639. this.blurY.alwaysForcePOT = true;
  61640. this.blurY.autoClear = false;
  61641. this.blurY.onActivateObservable.add(function () {
  61642. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61643. _this.blurY.kernel = _this.bloomKernel * dh;
  61644. });
  61645. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61646. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61647. this.copyBack.alwaysForcePOT = true;
  61648. if (this._hdr) {
  61649. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61650. var w = this.bloomWeight;
  61651. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61652. }
  61653. else {
  61654. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61655. }
  61656. this.copyBack.autoClear = false;
  61657. }
  61658. if (this._imageProcessingEnabled) {
  61659. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61660. if (this._hdr) {
  61661. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61662. }
  61663. else {
  61664. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61665. }
  61666. }
  61667. if (this.fxaaEnabled) {
  61668. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61669. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61670. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61671. }
  61672. else if (this._hdr && this.imageProcessing) {
  61673. this.finalMerge = this.imageProcessing;
  61674. }
  61675. else {
  61676. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61677. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61678. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61679. }
  61680. if (this.bloomEnabled) {
  61681. if (this._hdr) {
  61682. this.copyBack.shareOutputWith(this.blurX);
  61683. if (this.imageProcessing) {
  61684. this.imageProcessing.shareOutputWith(this.pass);
  61685. this.imageProcessing.autoClear = false;
  61686. }
  61687. else if (this.fxaa) {
  61688. this.fxaa.shareOutputWith(this.pass);
  61689. }
  61690. else {
  61691. this.finalMerge.shareOutputWith(this.pass);
  61692. }
  61693. }
  61694. else {
  61695. if (this.fxaa) {
  61696. this.fxaa.shareOutputWith(this.pass);
  61697. }
  61698. else {
  61699. this.finalMerge.shareOutputWith(this.pass);
  61700. }
  61701. }
  61702. }
  61703. if (this._cameras !== null) {
  61704. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61705. }
  61706. };
  61707. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61708. for (var i = 0; i < this._cameras.length; i++) {
  61709. var camera = this._cameras[i];
  61710. if (this.pass) {
  61711. this.pass.dispose(camera);
  61712. }
  61713. if (this.highlights) {
  61714. this.highlights.dispose(camera);
  61715. }
  61716. if (this.blurX) {
  61717. this.blurX.dispose(camera);
  61718. }
  61719. if (this.blurY) {
  61720. this.blurY.dispose(camera);
  61721. }
  61722. if (this.copyBack) {
  61723. this.copyBack.dispose(camera);
  61724. }
  61725. if (this.imageProcessing) {
  61726. this.imageProcessing.dispose(camera);
  61727. }
  61728. if (this.fxaa) {
  61729. this.fxaa.dispose(camera);
  61730. }
  61731. if (this.finalMerge) {
  61732. this.finalMerge.dispose(camera);
  61733. }
  61734. }
  61735. this.pass = null;
  61736. this.highlights = null;
  61737. this.blurX = null;
  61738. this.blurY = null;
  61739. this.copyBack = null;
  61740. this.imageProcessing = null;
  61741. this.fxaa = null;
  61742. this.finalMerge = null;
  61743. };
  61744. // Dispose
  61745. DefaultRenderingPipeline.prototype.dispose = function () {
  61746. this._disposePostProcesses();
  61747. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61748. _super.prototype.dispose.call(this);
  61749. };
  61750. // Serialize rendering pipeline
  61751. DefaultRenderingPipeline.prototype.serialize = function () {
  61752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61753. serializationObject.customType = "DefaultRenderingPipeline";
  61754. return serializationObject;
  61755. };
  61756. // Parse serialized pipeline
  61757. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61758. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61759. };
  61760. __decorate([
  61761. BABYLON.serialize()
  61762. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61763. __decorate([
  61764. BABYLON.serialize()
  61765. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61766. __decorate([
  61767. BABYLON.serialize()
  61768. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61769. __decorate([
  61770. BABYLON.serialize()
  61771. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61772. __decorate([
  61773. BABYLON.serialize()
  61774. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61775. __decorate([
  61776. BABYLON.serialize()
  61777. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61778. __decorate([
  61779. BABYLON.serialize()
  61780. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61781. __decorate([
  61782. BABYLON.serialize()
  61783. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61784. return DefaultRenderingPipeline;
  61785. }(BABYLON.PostProcessRenderPipeline));
  61786. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61787. })(BABYLON || (BABYLON = {}));
  61788. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61789. var BABYLON;
  61790. (function (BABYLON) {
  61791. var GeometryBufferRenderer = /** @class */ (function () {
  61792. function GeometryBufferRenderer(scene, ratio) {
  61793. if (ratio === void 0) { ratio = 1; }
  61794. this._enablePosition = false;
  61795. this._scene = scene;
  61796. this._ratio = ratio;
  61797. // Render target
  61798. this._createRenderTargets();
  61799. }
  61800. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61801. set: function (meshes) {
  61802. this._multiRenderTarget.renderList = meshes;
  61803. },
  61804. enumerable: true,
  61805. configurable: true
  61806. });
  61807. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61808. get: function () {
  61809. return this._multiRenderTarget.isSupported;
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61815. get: function () {
  61816. return this._enablePosition;
  61817. },
  61818. set: function (enable) {
  61819. this._enablePosition = enable;
  61820. this.dispose();
  61821. this._createRenderTargets();
  61822. },
  61823. enumerable: true,
  61824. configurable: true
  61825. });
  61826. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61827. var material = subMesh.getMaterial();
  61828. if (material && material.disableDepthWrite) {
  61829. return false;
  61830. }
  61831. var defines = [];
  61832. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61833. var mesh = subMesh.getMesh();
  61834. // Alpha test
  61835. if (material && material.needAlphaTesting()) {
  61836. defines.push("#define ALPHATEST");
  61837. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61838. attribs.push(BABYLON.VertexBuffer.UVKind);
  61839. defines.push("#define UV1");
  61840. }
  61841. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61842. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61843. defines.push("#define UV2");
  61844. }
  61845. }
  61846. // Buffers
  61847. if (this._enablePosition) {
  61848. defines.push("#define POSITION");
  61849. }
  61850. // Bones
  61851. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61852. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61853. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61854. if (mesh.numBoneInfluencers > 4) {
  61855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61857. }
  61858. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61859. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61860. }
  61861. else {
  61862. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61863. }
  61864. // Instances
  61865. if (useInstances) {
  61866. defines.push("#define INSTANCES");
  61867. attribs.push("world0");
  61868. attribs.push("world1");
  61869. attribs.push("world2");
  61870. attribs.push("world3");
  61871. }
  61872. // Get correct effect
  61873. var join = defines.join("\n");
  61874. if (this._cachedDefines !== join) {
  61875. this._cachedDefines = join;
  61876. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61877. }
  61878. return this._effect.isReady();
  61879. };
  61880. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61881. return this._multiRenderTarget;
  61882. };
  61883. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61884. get: function () {
  61885. return this._multiRenderTarget.samples;
  61886. },
  61887. set: function (value) {
  61888. this._multiRenderTarget.samples = value;
  61889. },
  61890. enumerable: true,
  61891. configurable: true
  61892. });
  61893. // Methods
  61894. GeometryBufferRenderer.prototype.dispose = function () {
  61895. this.getGBuffer().dispose();
  61896. };
  61897. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61898. var _this = this;
  61899. var engine = this._scene.getEngine();
  61900. var count = this._enablePosition ? 3 : 2;
  61901. 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 });
  61902. if (!this.isSupported) {
  61903. return;
  61904. }
  61905. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61906. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61907. this._multiRenderTarget.refreshRate = 1;
  61908. this._multiRenderTarget.renderParticles = false;
  61909. this._multiRenderTarget.renderList = null;
  61910. // set default depth value to 1.0 (far away)
  61911. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61912. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61913. });
  61914. // Custom render function
  61915. var renderSubMesh = function (subMesh) {
  61916. var mesh = subMesh.getRenderingMesh();
  61917. var scene = _this._scene;
  61918. var engine = scene.getEngine();
  61919. var material = subMesh.getMaterial();
  61920. if (!material) {
  61921. return;
  61922. }
  61923. // Culling
  61924. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61925. // Managing instances
  61926. var batch = mesh._getInstancesRenderList(subMesh._id);
  61927. if (batch.mustReturn) {
  61928. return;
  61929. }
  61930. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61931. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61932. engine.enableEffect(_this._effect);
  61933. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61934. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61935. _this._effect.setMatrix("view", scene.getViewMatrix());
  61936. // Alpha test
  61937. if (material && material.needAlphaTesting()) {
  61938. var alphaTexture = material.getAlphaTestTexture();
  61939. if (alphaTexture) {
  61940. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61941. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61942. }
  61943. }
  61944. // Bones
  61945. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61946. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61947. }
  61948. // Draw
  61949. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61950. }
  61951. };
  61952. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61953. var index;
  61954. if (depthOnlySubMeshes.length) {
  61955. engine.setColorWrite(false);
  61956. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61957. renderSubMesh(depthOnlySubMeshes.data[index]);
  61958. }
  61959. engine.setColorWrite(true);
  61960. }
  61961. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61962. renderSubMesh(opaqueSubMeshes.data[index]);
  61963. }
  61964. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61965. renderSubMesh(alphaTestSubMeshes.data[index]);
  61966. }
  61967. };
  61968. };
  61969. return GeometryBufferRenderer;
  61970. }());
  61971. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  61972. })(BABYLON || (BABYLON = {}));
  61973. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  61974. var BABYLON;
  61975. (function (BABYLON) {
  61976. var RefractionPostProcess = /** @class */ (function (_super) {
  61977. __extends(RefractionPostProcess, _super);
  61978. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  61979. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  61980. _this.color = color;
  61981. _this.depth = depth;
  61982. _this.colorLevel = colorLevel;
  61983. _this.onActivateObservable.add(function (cam) {
  61984. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  61985. });
  61986. _this.onApplyObservable.add(function (effect) {
  61987. effect.setColor3("baseColor", _this.color);
  61988. effect.setFloat("depth", _this.depth);
  61989. effect.setFloat("colorLevel", _this.colorLevel);
  61990. effect.setTexture("refractionSampler", _this._refRexture);
  61991. });
  61992. return _this;
  61993. }
  61994. // Methods
  61995. RefractionPostProcess.prototype.dispose = function (camera) {
  61996. if (this._refRexture) {
  61997. this._refRexture.dispose();
  61998. }
  61999. _super.prototype.dispose.call(this, camera);
  62000. };
  62001. return RefractionPostProcess;
  62002. }(BABYLON.PostProcess));
  62003. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62004. })(BABYLON || (BABYLON = {}));
  62005. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62006. var BABYLON;
  62007. (function (BABYLON) {
  62008. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62009. __extends(BlackAndWhitePostProcess, _super);
  62010. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62011. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62012. _this.degree = 1;
  62013. _this.onApplyObservable.add(function (effect) {
  62014. effect.setFloat("degree", _this.degree);
  62015. });
  62016. return _this;
  62017. }
  62018. return BlackAndWhitePostProcess;
  62019. }(BABYLON.PostProcess));
  62020. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62021. })(BABYLON || (BABYLON = {}));
  62022. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62023. var BABYLON;
  62024. (function (BABYLON) {
  62025. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62026. __extends(ConvolutionPostProcess, _super);
  62027. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62028. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62029. _this.kernel = kernel;
  62030. _this.onApply = function (effect) {
  62031. effect.setFloat2("screenSize", _this.width, _this.height);
  62032. effect.setArray("kernel", _this.kernel);
  62033. };
  62034. return _this;
  62035. }
  62036. // Statics
  62037. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62038. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62039. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62040. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62041. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62042. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62043. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62044. return ConvolutionPostProcess;
  62045. }(BABYLON.PostProcess));
  62046. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62047. })(BABYLON || (BABYLON = {}));
  62048. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62049. var BABYLON;
  62050. (function (BABYLON) {
  62051. var FilterPostProcess = /** @class */ (function (_super) {
  62052. __extends(FilterPostProcess, _super);
  62053. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62054. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62055. _this.kernelMatrix = kernelMatrix;
  62056. _this.onApply = function (effect) {
  62057. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62058. };
  62059. return _this;
  62060. }
  62061. return FilterPostProcess;
  62062. }(BABYLON.PostProcess));
  62063. BABYLON.FilterPostProcess = FilterPostProcess;
  62064. })(BABYLON || (BABYLON = {}));
  62065. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62066. var BABYLON;
  62067. (function (BABYLON) {
  62068. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62069. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62070. __extends(VolumetricLightScatteringPostProcess, _super);
  62071. /**
  62072. * @constructor
  62073. * @param {string} name - The post-process name
  62074. * @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)
  62075. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62076. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62077. * @param {number} samples - The post-process quality, default 100
  62078. * @param {number} samplingMode - The post-process filtering mode
  62079. * @param {BABYLON.Engine} engine - The babylon engine
  62080. * @param {boolean} reusable - If the post-process is reusable
  62081. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62082. */
  62083. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62084. if (samples === void 0) { samples = 100; }
  62085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62086. 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;
  62087. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62088. /**
  62089. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62090. * @type {Vector3}
  62091. */
  62092. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62093. /**
  62094. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62095. * @type {boolean}
  62096. */
  62097. _this.useCustomMeshPosition = false;
  62098. /**
  62099. * If the post-process should inverse the light scattering direction
  62100. * @type {boolean}
  62101. */
  62102. _this.invert = true;
  62103. /**
  62104. * Array containing the excluded meshes not rendered in the internal pass
  62105. */
  62106. _this.excludedMeshes = new Array();
  62107. /**
  62108. * Controls the overall intensity of the post-process
  62109. * @type {number}
  62110. */
  62111. _this.exposure = 0.3;
  62112. /**
  62113. * Dissipates each sample's contribution in range [0, 1]
  62114. * @type {number}
  62115. */
  62116. _this.decay = 0.96815;
  62117. /**
  62118. * Controls the overall intensity of each sample
  62119. * @type {number}
  62120. */
  62121. _this.weight = 0.58767;
  62122. /**
  62123. * Controls the density of each sample
  62124. * @type {number}
  62125. */
  62126. _this.density = 0.926;
  62127. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62128. engine = scene.getEngine();
  62129. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62130. // Configure mesh
  62131. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62132. // Configure
  62133. _this._createPass(scene, ratio.passRatio || ratio);
  62134. _this.onActivate = function (camera) {
  62135. if (!_this.isSupported) {
  62136. _this.dispose(camera);
  62137. }
  62138. _this.onActivate = null;
  62139. };
  62140. _this.onApplyObservable.add(function (effect) {
  62141. _this._updateMeshScreenCoordinates(scene);
  62142. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62143. effect.setFloat("exposure", _this.exposure);
  62144. effect.setFloat("decay", _this.decay);
  62145. effect.setFloat("weight", _this.weight);
  62146. effect.setFloat("density", _this.density);
  62147. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62148. });
  62149. return _this;
  62150. }
  62151. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62152. get: function () {
  62153. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62154. return false;
  62155. },
  62156. set: function (useDiffuseColor) {
  62157. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62158. },
  62159. enumerable: true,
  62160. configurable: true
  62161. });
  62162. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62163. return "VolumetricLightScatteringPostProcess";
  62164. };
  62165. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62166. var mesh = subMesh.getMesh();
  62167. // Render this.mesh as default
  62168. if (mesh === this.mesh && mesh.material) {
  62169. return mesh.material.isReady(mesh);
  62170. }
  62171. var defines = [];
  62172. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62173. var material = subMesh.getMaterial();
  62174. // Alpha test
  62175. if (material) {
  62176. if (material.needAlphaTesting()) {
  62177. defines.push("#define ALPHATEST");
  62178. }
  62179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62180. attribs.push(BABYLON.VertexBuffer.UVKind);
  62181. defines.push("#define UV1");
  62182. }
  62183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62185. defines.push("#define UV2");
  62186. }
  62187. }
  62188. // Bones
  62189. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62192. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62193. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62194. }
  62195. else {
  62196. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62197. }
  62198. // Instances
  62199. if (useInstances) {
  62200. defines.push("#define INSTANCES");
  62201. attribs.push("world0");
  62202. attribs.push("world1");
  62203. attribs.push("world2");
  62204. attribs.push("world3");
  62205. }
  62206. // Get correct effect
  62207. var join = defines.join("\n");
  62208. if (this._cachedDefines !== join) {
  62209. this._cachedDefines = join;
  62210. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62211. }
  62212. return this._volumetricLightScatteringPass.isReady();
  62213. };
  62214. /**
  62215. * Sets the new light position for light scattering effect
  62216. * @param {BABYLON.Vector3} The new custom light position
  62217. */
  62218. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62219. this.customMeshPosition = position;
  62220. };
  62221. /**
  62222. * Returns the light position for light scattering effect
  62223. * @return {BABYLON.Vector3} The custom light position
  62224. */
  62225. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62226. return this.customMeshPosition;
  62227. };
  62228. /**
  62229. * Disposes the internal assets and detaches the post-process from the camera
  62230. */
  62231. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62232. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62233. if (rttIndex !== -1) {
  62234. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62235. }
  62236. this._volumetricLightScatteringRTT.dispose();
  62237. _super.prototype.dispose.call(this, camera);
  62238. };
  62239. /**
  62240. * Returns the render target texture used by the post-process
  62241. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62242. */
  62243. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62244. return this._volumetricLightScatteringRTT;
  62245. };
  62246. // Private methods
  62247. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62248. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62249. return true;
  62250. }
  62251. return false;
  62252. };
  62253. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62254. var _this = this;
  62255. var engine = scene.getEngine();
  62256. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62257. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62258. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62259. this._volumetricLightScatteringRTT.renderList = null;
  62260. this._volumetricLightScatteringRTT.renderParticles = false;
  62261. var camera = this.getCamera();
  62262. if (camera) {
  62263. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62264. }
  62265. else {
  62266. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62267. }
  62268. // Custom render function for submeshes
  62269. var renderSubMesh = function (subMesh) {
  62270. var mesh = subMesh.getRenderingMesh();
  62271. if (_this._meshExcluded(mesh)) {
  62272. return;
  62273. }
  62274. var material = subMesh.getMaterial();
  62275. if (!material) {
  62276. return;
  62277. }
  62278. var scene = mesh.getScene();
  62279. var engine = scene.getEngine();
  62280. // Culling
  62281. engine.setState(material.backFaceCulling);
  62282. // Managing instances
  62283. var batch = mesh._getInstancesRenderList(subMesh._id);
  62284. if (batch.mustReturn) {
  62285. return;
  62286. }
  62287. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62288. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62289. var effect = _this._volumetricLightScatteringPass;
  62290. if (mesh === _this.mesh) {
  62291. if (subMesh.effect) {
  62292. effect = subMesh.effect;
  62293. }
  62294. else {
  62295. effect = material.getEffect();
  62296. }
  62297. }
  62298. engine.enableEffect(effect);
  62299. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62300. if (mesh === _this.mesh) {
  62301. material.bind(mesh.getWorldMatrix(), mesh);
  62302. }
  62303. else {
  62304. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62305. // Alpha test
  62306. if (material && material.needAlphaTesting()) {
  62307. var alphaTexture = material.getAlphaTestTexture();
  62308. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62309. if (alphaTexture) {
  62310. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62311. }
  62312. }
  62313. // Bones
  62314. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62315. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62316. }
  62317. }
  62318. // Draw
  62319. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62320. }
  62321. };
  62322. // Render target texture callbacks
  62323. var savedSceneClearColor;
  62324. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62325. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62326. savedSceneClearColor = scene.clearColor;
  62327. scene.clearColor = sceneClearColor;
  62328. });
  62329. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62330. scene.clearColor = savedSceneClearColor;
  62331. });
  62332. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62333. var engine = scene.getEngine();
  62334. var index;
  62335. if (depthOnlySubMeshes.length) {
  62336. engine.setColorWrite(false);
  62337. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62338. renderSubMesh(depthOnlySubMeshes.data[index]);
  62339. }
  62340. engine.setColorWrite(true);
  62341. }
  62342. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62343. renderSubMesh(opaqueSubMeshes.data[index]);
  62344. }
  62345. engine.setAlphaTesting(true);
  62346. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62347. renderSubMesh(alphaTestSubMeshes.data[index]);
  62348. }
  62349. engine.setAlphaTesting(false);
  62350. if (transparentSubMeshes.length) {
  62351. // Sort sub meshes
  62352. for (index = 0; index < transparentSubMeshes.length; index++) {
  62353. var submesh = transparentSubMeshes.data[index];
  62354. var boundingInfo = submesh.getBoundingInfo();
  62355. if (boundingInfo && scene.activeCamera) {
  62356. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62357. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62358. }
  62359. }
  62360. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62361. sortedArray.sort(function (a, b) {
  62362. // Alpha index first
  62363. if (a._alphaIndex > b._alphaIndex) {
  62364. return 1;
  62365. }
  62366. if (a._alphaIndex < b._alphaIndex) {
  62367. return -1;
  62368. }
  62369. // Then distance to camera
  62370. if (a._distanceToCamera < b._distanceToCamera) {
  62371. return 1;
  62372. }
  62373. if (a._distanceToCamera > b._distanceToCamera) {
  62374. return -1;
  62375. }
  62376. return 0;
  62377. });
  62378. // Render sub meshes
  62379. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62380. for (index = 0; index < sortedArray.length; index++) {
  62381. renderSubMesh(sortedArray[index]);
  62382. }
  62383. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62384. }
  62385. };
  62386. };
  62387. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62388. var transform = scene.getTransformMatrix();
  62389. var meshPosition;
  62390. if (this.useCustomMeshPosition) {
  62391. meshPosition = this.customMeshPosition;
  62392. }
  62393. else if (this.attachedNode) {
  62394. meshPosition = this.attachedNode.position;
  62395. }
  62396. else {
  62397. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62398. }
  62399. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62400. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62401. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62402. if (this.invert)
  62403. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62404. };
  62405. // Static methods
  62406. /**
  62407. * Creates a default mesh for the Volumeric Light Scattering post-process
  62408. * @param {string} The mesh name
  62409. * @param {BABYLON.Scene} The scene where to create the mesh
  62410. * @return {BABYLON.Mesh} the default mesh
  62411. */
  62412. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62413. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62414. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62415. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62416. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62417. mesh.material = material;
  62418. return mesh;
  62419. };
  62420. __decorate([
  62421. BABYLON.serializeAsVector3()
  62422. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62423. __decorate([
  62424. BABYLON.serialize()
  62425. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62426. __decorate([
  62427. BABYLON.serialize()
  62428. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62429. __decorate([
  62430. BABYLON.serializeAsMeshReference()
  62431. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62432. __decorate([
  62433. BABYLON.serialize()
  62434. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62435. __decorate([
  62436. BABYLON.serialize()
  62437. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62438. __decorate([
  62439. BABYLON.serialize()
  62440. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62441. __decorate([
  62442. BABYLON.serialize()
  62443. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62444. __decorate([
  62445. BABYLON.serialize()
  62446. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62447. return VolumetricLightScatteringPostProcess;
  62448. }(BABYLON.PostProcess));
  62449. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62450. })(BABYLON || (BABYLON = {}));
  62451. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62452. //
  62453. // This post-process allows the modification of rendered colors by using
  62454. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62455. //
  62456. // The object needs to be provided an url to a texture containing the color
  62457. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62458. // Use an image editing software to tweak the LUT to match your needs.
  62459. //
  62460. // For an example of a color LUT, see here:
  62461. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62462. // For explanations on color grading, see here:
  62463. // http://udn.epicgames.com/Three/ColorGrading.html
  62464. //
  62465. var BABYLON;
  62466. (function (BABYLON) {
  62467. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62468. __extends(ColorCorrectionPostProcess, _super);
  62469. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62470. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62471. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62472. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62473. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62474. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62475. _this.onApply = function (effect) {
  62476. effect.setTexture("colorTable", _this._colorTableTexture);
  62477. };
  62478. return _this;
  62479. }
  62480. return ColorCorrectionPostProcess;
  62481. }(BABYLON.PostProcess));
  62482. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62483. })(BABYLON || (BABYLON = {}));
  62484. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62485. var BABYLON;
  62486. (function (BABYLON) {
  62487. var TonemappingOperator;
  62488. (function (TonemappingOperator) {
  62489. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62490. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62491. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62492. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62493. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62494. ;
  62495. var TonemapPostProcess = /** @class */ (function (_super) {
  62496. __extends(TonemapPostProcess, _super);
  62497. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62499. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62500. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62501. _this._operator = _operator;
  62502. _this.exposureAdjustment = exposureAdjustment;
  62503. var defines = "#define ";
  62504. if (_this._operator === TonemappingOperator.Hable)
  62505. defines += "HABLE_TONEMAPPING";
  62506. else if (_this._operator === TonemappingOperator.Reinhard)
  62507. defines += "REINHARD_TONEMAPPING";
  62508. else if (_this._operator === TonemappingOperator.HejiDawson)
  62509. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62510. else if (_this._operator === TonemappingOperator.Photographic)
  62511. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62512. //sadly a second call to create the effect.
  62513. _this.updateEffect(defines);
  62514. _this.onApply = function (effect) {
  62515. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62516. };
  62517. return _this;
  62518. }
  62519. return TonemapPostProcess;
  62520. }(BABYLON.PostProcess));
  62521. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62522. })(BABYLON || (BABYLON = {}));
  62523. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62524. var BABYLON;
  62525. (function (BABYLON) {
  62526. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62527. __extends(DisplayPassPostProcess, _super);
  62528. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62529. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62530. }
  62531. return DisplayPassPostProcess;
  62532. }(BABYLON.PostProcess));
  62533. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62534. })(BABYLON || (BABYLON = {}));
  62535. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62536. var BABYLON;
  62537. (function (BABYLON) {
  62538. var HighlightsPostProcess = /** @class */ (function (_super) {
  62539. __extends(HighlightsPostProcess, _super);
  62540. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62541. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62542. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62543. }
  62544. return HighlightsPostProcess;
  62545. }(BABYLON.PostProcess));
  62546. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62547. })(BABYLON || (BABYLON = {}));
  62548. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62549. var BABYLON;
  62550. (function (BABYLON) {
  62551. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62552. __extends(ImageProcessingPostProcess, _super);
  62553. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62554. if (camera === void 0) { camera = null; }
  62555. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62556. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62557. _this._fromLinearSpace = true;
  62558. /**
  62559. * Defines cache preventing GC.
  62560. */
  62561. _this._defines = {
  62562. IMAGEPROCESSING: false,
  62563. VIGNETTE: false,
  62564. VIGNETTEBLENDMODEMULTIPLY: false,
  62565. VIGNETTEBLENDMODEOPAQUE: false,
  62566. TONEMAPPING: false,
  62567. CONTRAST: false,
  62568. COLORCURVES: false,
  62569. COLORGRADING: false,
  62570. COLORGRADING3D: false,
  62571. FROMLINEARSPACE: false,
  62572. SAMPLER3DGREENDEPTH: false,
  62573. SAMPLER3DBGRMAP: false,
  62574. IMAGEPROCESSINGPOSTPROCESS: false,
  62575. EXPOSURE: false,
  62576. };
  62577. // Setup the configuration as forced by the constructor. This would then not force the
  62578. // scene materials output in linear space and let untouched the default forward pass.
  62579. if (imageProcessingConfiguration) {
  62580. imageProcessingConfiguration.applyByPostProcess = true;
  62581. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62582. // This will cause the shader to be compiled
  62583. _this.fromLinearSpace = false;
  62584. }
  62585. else {
  62586. _this._attachImageProcessingConfiguration(null, true);
  62587. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62588. }
  62589. _this.onApply = function (effect) {
  62590. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62591. };
  62592. return _this;
  62593. }
  62594. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62595. /**
  62596. * Gets the image processing configuration used either in this material.
  62597. */
  62598. get: function () {
  62599. return this._imageProcessingConfiguration;
  62600. },
  62601. /**
  62602. * Sets the Default image processing configuration used either in the this material.
  62603. *
  62604. * If sets to null, the scene one is in use.
  62605. */
  62606. set: function (value) {
  62607. this._attachImageProcessingConfiguration(value);
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. /**
  62613. * Attaches a new image processing configuration to the PBR Material.
  62614. * @param configuration
  62615. */
  62616. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62617. var _this = this;
  62618. if (doNotBuild === void 0) { doNotBuild = false; }
  62619. if (configuration === this._imageProcessingConfiguration) {
  62620. return;
  62621. }
  62622. // Detaches observer.
  62623. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62624. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62625. }
  62626. // Pick the scene configuration if needed.
  62627. if (!configuration) {
  62628. var scene = null;
  62629. var engine = this.getEngine();
  62630. var camera = this.getCamera();
  62631. if (camera) {
  62632. scene = camera.getScene();
  62633. }
  62634. else if (engine && engine.scenes) {
  62635. var scenes = engine.scenes;
  62636. scene = scenes[scenes.length - 1];
  62637. }
  62638. else {
  62639. scene = BABYLON.Engine.LastCreatedScene;
  62640. }
  62641. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62642. }
  62643. else {
  62644. this._imageProcessingConfiguration = configuration;
  62645. }
  62646. // Attaches observer.
  62647. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62648. _this._updateParameters();
  62649. });
  62650. // Ensure the effect will be rebuilt.
  62651. if (!doNotBuild) {
  62652. this._updateParameters();
  62653. }
  62654. };
  62655. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62656. /**
  62657. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62658. */
  62659. get: function () {
  62660. return this.imageProcessingConfiguration.colorCurves;
  62661. },
  62662. /**
  62663. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62664. */
  62665. set: function (value) {
  62666. this.imageProcessingConfiguration.colorCurves = value;
  62667. },
  62668. enumerable: true,
  62669. configurable: true
  62670. });
  62671. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62672. /**
  62673. * Gets wether the color curves effect is enabled.
  62674. */
  62675. get: function () {
  62676. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62677. },
  62678. /**
  62679. * Sets wether the color curves effect is enabled.
  62680. */
  62681. set: function (value) {
  62682. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62683. },
  62684. enumerable: true,
  62685. configurable: true
  62686. });
  62687. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62688. /**
  62689. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62690. */
  62691. get: function () {
  62692. return this.imageProcessingConfiguration.colorGradingTexture;
  62693. },
  62694. /**
  62695. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62696. */
  62697. set: function (value) {
  62698. this.imageProcessingConfiguration.colorGradingTexture = value;
  62699. },
  62700. enumerable: true,
  62701. configurable: true
  62702. });
  62703. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62704. /**
  62705. * Gets wether the color grading effect is enabled.
  62706. */
  62707. get: function () {
  62708. return this.imageProcessingConfiguration.colorGradingEnabled;
  62709. },
  62710. /**
  62711. * Gets wether the color grading effect is enabled.
  62712. */
  62713. set: function (value) {
  62714. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62715. },
  62716. enumerable: true,
  62717. configurable: true
  62718. });
  62719. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62720. /**
  62721. * Gets exposure used in the effect.
  62722. */
  62723. get: function () {
  62724. return this.imageProcessingConfiguration.exposure;
  62725. },
  62726. /**
  62727. * Sets exposure used in the effect.
  62728. */
  62729. set: function (value) {
  62730. this.imageProcessingConfiguration.exposure = value;
  62731. },
  62732. enumerable: true,
  62733. configurable: true
  62734. });
  62735. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62736. /**
  62737. * Gets wether tonemapping is enabled or not.
  62738. */
  62739. get: function () {
  62740. return this._imageProcessingConfiguration.toneMappingEnabled;
  62741. },
  62742. /**
  62743. * Sets wether tonemapping is enabled or not
  62744. */
  62745. set: function (value) {
  62746. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62747. },
  62748. enumerable: true,
  62749. configurable: true
  62750. });
  62751. ;
  62752. ;
  62753. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62754. /**
  62755. * Gets contrast used in the effect.
  62756. */
  62757. get: function () {
  62758. return this.imageProcessingConfiguration.contrast;
  62759. },
  62760. /**
  62761. * Sets contrast used in the effect.
  62762. */
  62763. set: function (value) {
  62764. this.imageProcessingConfiguration.contrast = value;
  62765. },
  62766. enumerable: true,
  62767. configurable: true
  62768. });
  62769. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62770. /**
  62771. * Gets Vignette stretch size.
  62772. */
  62773. get: function () {
  62774. return this.imageProcessingConfiguration.vignetteStretch;
  62775. },
  62776. /**
  62777. * Sets Vignette stretch size.
  62778. */
  62779. set: function (value) {
  62780. this.imageProcessingConfiguration.vignetteStretch = value;
  62781. },
  62782. enumerable: true,
  62783. configurable: true
  62784. });
  62785. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62786. /**
  62787. * Gets Vignette centre X Offset.
  62788. */
  62789. get: function () {
  62790. return this.imageProcessingConfiguration.vignetteCentreX;
  62791. },
  62792. /**
  62793. * Sets Vignette centre X Offset.
  62794. */
  62795. set: function (value) {
  62796. this.imageProcessingConfiguration.vignetteCentreX = value;
  62797. },
  62798. enumerable: true,
  62799. configurable: true
  62800. });
  62801. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62802. /**
  62803. * Gets Vignette centre Y Offset.
  62804. */
  62805. get: function () {
  62806. return this.imageProcessingConfiguration.vignetteCentreY;
  62807. },
  62808. /**
  62809. * Sets Vignette centre Y Offset.
  62810. */
  62811. set: function (value) {
  62812. this.imageProcessingConfiguration.vignetteCentreY = value;
  62813. },
  62814. enumerable: true,
  62815. configurable: true
  62816. });
  62817. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62818. /**
  62819. * Gets Vignette weight or intensity of the vignette effect.
  62820. */
  62821. get: function () {
  62822. return this.imageProcessingConfiguration.vignetteWeight;
  62823. },
  62824. /**
  62825. * Sets Vignette weight or intensity of the vignette effect.
  62826. */
  62827. set: function (value) {
  62828. this.imageProcessingConfiguration.vignetteWeight = value;
  62829. },
  62830. enumerable: true,
  62831. configurable: true
  62832. });
  62833. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62834. /**
  62835. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62836. * if vignetteEnabled is set to true.
  62837. */
  62838. get: function () {
  62839. return this.imageProcessingConfiguration.vignetteColor;
  62840. },
  62841. /**
  62842. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62843. * if vignetteEnabled is set to true.
  62844. */
  62845. set: function (value) {
  62846. this.imageProcessingConfiguration.vignetteColor = value;
  62847. },
  62848. enumerable: true,
  62849. configurable: true
  62850. });
  62851. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62852. /**
  62853. * Gets Camera field of view used by the Vignette effect.
  62854. */
  62855. get: function () {
  62856. return this.imageProcessingConfiguration.vignetteCameraFov;
  62857. },
  62858. /**
  62859. * Sets Camera field of view used by the Vignette effect.
  62860. */
  62861. set: function (value) {
  62862. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62863. },
  62864. enumerable: true,
  62865. configurable: true
  62866. });
  62867. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62868. /**
  62869. * Gets the vignette blend mode allowing different kind of effect.
  62870. */
  62871. get: function () {
  62872. return this.imageProcessingConfiguration.vignetteBlendMode;
  62873. },
  62874. /**
  62875. * Sets the vignette blend mode allowing different kind of effect.
  62876. */
  62877. set: function (value) {
  62878. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62879. },
  62880. enumerable: true,
  62881. configurable: true
  62882. });
  62883. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62884. /**
  62885. * Gets wether the vignette effect is enabled.
  62886. */
  62887. get: function () {
  62888. return this.imageProcessingConfiguration.vignetteEnabled;
  62889. },
  62890. /**
  62891. * Sets wether the vignette effect is enabled.
  62892. */
  62893. set: function (value) {
  62894. this.imageProcessingConfiguration.vignetteEnabled = value;
  62895. },
  62896. enumerable: true,
  62897. configurable: true
  62898. });
  62899. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62900. /**
  62901. * Gets wether the input of the processing is in Gamma or Linear Space.
  62902. */
  62903. get: function () {
  62904. return this._fromLinearSpace;
  62905. },
  62906. /**
  62907. * Sets wether the input of the processing is in Gamma or Linear Space.
  62908. */
  62909. set: function (value) {
  62910. if (this._fromLinearSpace === value) {
  62911. return;
  62912. }
  62913. this._fromLinearSpace = value;
  62914. this._updateParameters();
  62915. },
  62916. enumerable: true,
  62917. configurable: true
  62918. });
  62919. ImageProcessingPostProcess.prototype.getClassName = function () {
  62920. return "ImageProcessingPostProcess";
  62921. };
  62922. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62923. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62924. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62925. var defines = "";
  62926. for (var define in this._defines) {
  62927. if (this._defines[define]) {
  62928. defines += "#define " + define + ";\r\n";
  62929. }
  62930. }
  62931. var samplers = ["textureSampler"];
  62932. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62933. var uniforms = ["scale"];
  62934. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62935. this.updateEffect(defines, uniforms, samplers);
  62936. };
  62937. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62938. _super.prototype.dispose.call(this, camera);
  62939. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62940. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62941. }
  62942. this.imageProcessingConfiguration.applyByPostProcess = false;
  62943. };
  62944. __decorate([
  62945. BABYLON.serialize()
  62946. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62947. return ImageProcessingPostProcess;
  62948. }(BABYLON.PostProcess));
  62949. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62950. })(BABYLON || (BABYLON = {}));
  62951. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62952. var BABYLON;
  62953. (function (BABYLON) {
  62954. var BlurPostProcess = /** @class */ (function (_super) {
  62955. __extends(BlurPostProcess, _super);
  62956. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62958. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62959. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62960. _this.direction = direction;
  62961. _this._packedFloat = false;
  62962. _this.onApplyObservable.add(function (effect) {
  62963. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62964. });
  62965. _this.kernel = kernel;
  62966. return _this;
  62967. }
  62968. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  62969. /**
  62970. * Gets the length in pixels of the blur sample region
  62971. */
  62972. get: function () {
  62973. return this._idealKernel;
  62974. },
  62975. /**
  62976. * Sets the length in pixels of the blur sample region
  62977. */
  62978. set: function (v) {
  62979. if (this._idealKernel === v) {
  62980. return;
  62981. }
  62982. v = Math.max(v, 1);
  62983. this._idealKernel = v;
  62984. this._kernel = this._nearestBestKernel(v);
  62985. this._updateParameters();
  62986. },
  62987. enumerable: true,
  62988. configurable: true
  62989. });
  62990. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  62991. /**
  62992. * Gets wether or not the blur is unpacking/repacking floats
  62993. */
  62994. get: function () {
  62995. return this._packedFloat;
  62996. },
  62997. /**
  62998. * Sets wether or not the blur needs to unpack/repack floats
  62999. */
  63000. set: function (v) {
  63001. if (this._packedFloat === v) {
  63002. return;
  63003. }
  63004. this._packedFloat = v;
  63005. this._updateParameters();
  63006. },
  63007. enumerable: true,
  63008. configurable: true
  63009. });
  63010. BlurPostProcess.prototype._updateParameters = function () {
  63011. // Generate sampling offsets and weights
  63012. var N = this._kernel;
  63013. var centerIndex = (N - 1) / 2;
  63014. // Generate Gaussian sampling weights over kernel
  63015. var offsets = [];
  63016. var weights = [];
  63017. var totalWeight = 0;
  63018. for (var i = 0; i < N; i++) {
  63019. var u = i / (N - 1);
  63020. var w = this._gaussianWeight(u * 2.0 - 1);
  63021. offsets[i] = (i - centerIndex);
  63022. weights[i] = w;
  63023. totalWeight += w;
  63024. }
  63025. // Normalize weights
  63026. for (var i = 0; i < weights.length; i++) {
  63027. weights[i] /= totalWeight;
  63028. }
  63029. // Optimize: combine samples to take advantage of hardware linear sampling
  63030. // Walk from left to center, combining pairs (symmetrically)
  63031. var linearSamplingWeights = [];
  63032. var linearSamplingOffsets = [];
  63033. var linearSamplingMap = [];
  63034. for (var i = 0; i <= centerIndex; i += 2) {
  63035. var j = Math.min(i + 1, Math.floor(centerIndex));
  63036. var singleCenterSample = i === j;
  63037. if (singleCenterSample) {
  63038. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63039. }
  63040. else {
  63041. var sharedCell = j === centerIndex;
  63042. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63043. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63044. if (offsetLinear === 0) {
  63045. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63046. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63047. }
  63048. else {
  63049. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63050. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63051. }
  63052. }
  63053. }
  63054. for (var i = 0; i < linearSamplingMap.length; i++) {
  63055. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63056. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63057. }
  63058. // Replace with optimized
  63059. offsets = linearSamplingOffsets;
  63060. weights = linearSamplingWeights;
  63061. // Generate shaders
  63062. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63063. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63064. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63065. var defines = "";
  63066. for (var i = 0; i < varyingCount; i++) {
  63067. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63068. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63069. }
  63070. var depCount = 0;
  63071. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63072. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63073. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63074. depCount++;
  63075. }
  63076. if (this.packedFloat) {
  63077. defines += "#define PACKEDFLOAT 1";
  63078. }
  63079. this.updateEffect(defines, null, null, {
  63080. varyingCount: varyingCount,
  63081. depCount: depCount
  63082. });
  63083. };
  63084. /**
  63085. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63086. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63087. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63088. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63089. * The gaps between physical kernels are compensated for in the weighting of the samples
  63090. * @param idealKernel Ideal blur kernel.
  63091. * @return Nearest best kernel.
  63092. */
  63093. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63094. var v = Math.round(idealKernel);
  63095. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63096. var k = _a[_i];
  63097. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63098. return Math.max(k, 3);
  63099. }
  63100. }
  63101. return Math.max(v, 3);
  63102. };
  63103. /**
  63104. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63105. * @param x The point on the Gaussian distribution to sample.
  63106. * @return the value of the Gaussian function at x.
  63107. */
  63108. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63109. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63110. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63111. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63112. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63113. // truncated at around 1.3% of peak strength.
  63114. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63115. var sigma = (1 / 3);
  63116. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63117. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63118. var weight = (1.0 / denominator) * Math.exp(exponent);
  63119. return weight;
  63120. };
  63121. /**
  63122. * Generates a string that can be used as a floating point number in GLSL.
  63123. * @param x Value to print.
  63124. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63125. * @return GLSL float string.
  63126. */
  63127. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63128. if (decimalFigures === void 0) { decimalFigures = 8; }
  63129. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63130. };
  63131. return BlurPostProcess;
  63132. }(BABYLON.PostProcess));
  63133. BABYLON.BlurPostProcess = BlurPostProcess;
  63134. })(BABYLON || (BABYLON = {}));
  63135. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63136. var BABYLON;
  63137. (function (BABYLON) {
  63138. var Bone = /** @class */ (function (_super) {
  63139. __extends(Bone, _super);
  63140. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63141. if (parentBone === void 0) { parentBone = null; }
  63142. if (localMatrix === void 0) { localMatrix = null; }
  63143. if (restPose === void 0) { restPose = null; }
  63144. if (baseMatrix === void 0) { baseMatrix = null; }
  63145. if (index === void 0) { index = null; }
  63146. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63147. _this.name = name;
  63148. _this.children = new Array();
  63149. _this.animations = new Array();
  63150. // Set this value to map this bone to a different index in the transform matrices.
  63151. // Set this value to -1 to exclude the bone from the transform matrices.
  63152. _this._index = null;
  63153. _this._worldTransform = new BABYLON.Matrix();
  63154. _this._absoluteTransform = new BABYLON.Matrix();
  63155. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63156. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63157. _this._scaleVector = BABYLON.Vector3.One();
  63158. _this._negateScaleChildren = BABYLON.Vector3.One();
  63159. _this._scalingDeterminant = 1;
  63160. _this._skeleton = skeleton;
  63161. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63162. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63163. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63164. _this._index = index;
  63165. skeleton.bones.push(_this);
  63166. _this.setParent(parentBone, false);
  63167. _this._updateDifferenceMatrix();
  63168. return _this;
  63169. }
  63170. Object.defineProperty(Bone.prototype, "_matrix", {
  63171. get: function () {
  63172. return this._localMatrix;
  63173. },
  63174. set: function (val) {
  63175. if (this._localMatrix) {
  63176. this._localMatrix.copyFrom(val);
  63177. }
  63178. else {
  63179. this._localMatrix = val;
  63180. }
  63181. },
  63182. enumerable: true,
  63183. configurable: true
  63184. });
  63185. // Members
  63186. Bone.prototype.getSkeleton = function () {
  63187. return this._skeleton;
  63188. };
  63189. Bone.prototype.getParent = function () {
  63190. return this._parent;
  63191. };
  63192. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63193. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63194. if (this._parent === parent) {
  63195. return;
  63196. }
  63197. if (this._parent) {
  63198. var index = this._parent.children.indexOf(this);
  63199. if (index !== -1) {
  63200. this._parent.children.splice(index, 1);
  63201. }
  63202. }
  63203. this._parent = parent;
  63204. if (this._parent) {
  63205. this._parent.children.push(this);
  63206. }
  63207. if (updateDifferenceMatrix) {
  63208. this._updateDifferenceMatrix();
  63209. }
  63210. };
  63211. Bone.prototype.getLocalMatrix = function () {
  63212. return this._localMatrix;
  63213. };
  63214. Bone.prototype.getBaseMatrix = function () {
  63215. return this._baseMatrix;
  63216. };
  63217. Bone.prototype.getRestPose = function () {
  63218. return this._restPose;
  63219. };
  63220. Bone.prototype.returnToRest = function () {
  63221. this.updateMatrix(this._restPose.clone());
  63222. };
  63223. Bone.prototype.getWorldMatrix = function () {
  63224. return this._worldTransform;
  63225. };
  63226. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63227. return this._invertedAbsoluteTransform;
  63228. };
  63229. Bone.prototype.getAbsoluteTransform = function () {
  63230. return this._absoluteTransform;
  63231. };
  63232. Object.defineProperty(Bone.prototype, "position", {
  63233. // Properties (matches AbstractMesh properties)
  63234. get: function () {
  63235. return this.getPosition();
  63236. },
  63237. set: function (newPosition) {
  63238. this.setPosition(newPosition);
  63239. },
  63240. enumerable: true,
  63241. configurable: true
  63242. });
  63243. Object.defineProperty(Bone.prototype, "rotation", {
  63244. get: function () {
  63245. return this.getRotation();
  63246. },
  63247. set: function (newRotation) {
  63248. this.setRotation(newRotation);
  63249. },
  63250. enumerable: true,
  63251. configurable: true
  63252. });
  63253. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63254. get: function () {
  63255. return this.getRotationQuaternion();
  63256. },
  63257. set: function (newRotation) {
  63258. this.setRotationQuaternion(newRotation);
  63259. },
  63260. enumerable: true,
  63261. configurable: true
  63262. });
  63263. Object.defineProperty(Bone.prototype, "scaling", {
  63264. get: function () {
  63265. return this.getScale();
  63266. },
  63267. set: function (newScaling) {
  63268. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63269. },
  63270. enumerable: true,
  63271. configurable: true
  63272. });
  63273. // Methods
  63274. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63275. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63276. this._baseMatrix = matrix.clone();
  63277. this._localMatrix = matrix.clone();
  63278. this._skeleton._markAsDirty();
  63279. if (updateDifferenceMatrix) {
  63280. this._updateDifferenceMatrix();
  63281. }
  63282. };
  63283. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63284. if (!rootMatrix) {
  63285. rootMatrix = this._baseMatrix;
  63286. }
  63287. if (this._parent) {
  63288. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63289. }
  63290. else {
  63291. this._absoluteTransform.copyFrom(rootMatrix);
  63292. }
  63293. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63294. for (var index = 0; index < this.children.length; index++) {
  63295. this.children[index]._updateDifferenceMatrix();
  63296. }
  63297. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63298. };
  63299. Bone.prototype.markAsDirty = function () {
  63300. this._currentRenderId++;
  63301. this._skeleton._markAsDirty();
  63302. };
  63303. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63304. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63305. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63306. // all animation may be coming from a library skeleton, so may need to create animation
  63307. if (this.animations.length === 0) {
  63308. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63309. this.animations[0].setKeys([]);
  63310. }
  63311. // get animation info / verify there is such a range from the source bone
  63312. var sourceRange = source.animations[0].getRange(rangeName);
  63313. if (!sourceRange) {
  63314. return false;
  63315. }
  63316. var from = sourceRange.from;
  63317. var to = sourceRange.to;
  63318. var sourceKeys = source.animations[0].getKeys();
  63319. // rescaling prep
  63320. var sourceBoneLength = source.length;
  63321. var sourceParent = source.getParent();
  63322. var parent = this.getParent();
  63323. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63324. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63325. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63326. var destKeys = this.animations[0].getKeys();
  63327. // loop vars declaration
  63328. var orig;
  63329. var origTranslation;
  63330. var mat;
  63331. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63332. orig = sourceKeys[key];
  63333. if (orig.frame >= from && orig.frame <= to) {
  63334. if (rescaleAsRequired) {
  63335. mat = orig.value.clone();
  63336. // scale based on parent ratio, when bone has parent
  63337. if (parentScalingReqd) {
  63338. origTranslation = mat.getTranslation();
  63339. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63340. // scale based on skeleton dimension ratio when root bone, and value is passed
  63341. }
  63342. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63343. origTranslation = mat.getTranslation();
  63344. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63345. // use original when root bone, and no data for skelDimensionsRatio
  63346. }
  63347. else {
  63348. mat = orig.value;
  63349. }
  63350. }
  63351. else {
  63352. mat = orig.value;
  63353. }
  63354. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63355. }
  63356. }
  63357. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63358. return true;
  63359. };
  63360. /**
  63361. * Translate the bone in local or world space.
  63362. * @param vec The amount to translate the bone.
  63363. * @param space The space that the translation is in.
  63364. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63365. */
  63366. Bone.prototype.translate = function (vec, space, mesh) {
  63367. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63368. var lm = this.getLocalMatrix();
  63369. if (space == BABYLON.Space.LOCAL) {
  63370. lm.m[12] += vec.x;
  63371. lm.m[13] += vec.y;
  63372. lm.m[14] += vec.z;
  63373. }
  63374. else {
  63375. var wm = null;
  63376. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63377. if (mesh) {
  63378. wm = mesh.getWorldMatrix();
  63379. }
  63380. this._skeleton.computeAbsoluteTransforms();
  63381. var tmat = Bone._tmpMats[0];
  63382. var tvec = Bone._tmpVecs[0];
  63383. if (this._parent) {
  63384. if (mesh && wm) {
  63385. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63386. tmat.multiplyToRef(wm, tmat);
  63387. }
  63388. else {
  63389. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63390. }
  63391. }
  63392. tmat.m[12] = 0;
  63393. tmat.m[13] = 0;
  63394. tmat.m[14] = 0;
  63395. tmat.invert();
  63396. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63397. lm.m[12] += tvec.x;
  63398. lm.m[13] += tvec.y;
  63399. lm.m[14] += tvec.z;
  63400. }
  63401. this.markAsDirty();
  63402. };
  63403. /**
  63404. * Set the postion of the bone in local or world space.
  63405. * @param position The position to set the bone.
  63406. * @param space The space that the position is in.
  63407. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63408. */
  63409. Bone.prototype.setPosition = function (position, space, mesh) {
  63410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63411. var lm = this.getLocalMatrix();
  63412. if (space == BABYLON.Space.LOCAL) {
  63413. lm.m[12] = position.x;
  63414. lm.m[13] = position.y;
  63415. lm.m[14] = position.z;
  63416. }
  63417. else {
  63418. var wm = null;
  63419. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63420. if (mesh) {
  63421. wm = mesh.getWorldMatrix();
  63422. }
  63423. this._skeleton.computeAbsoluteTransforms();
  63424. var tmat = Bone._tmpMats[0];
  63425. var vec = Bone._tmpVecs[0];
  63426. if (this._parent) {
  63427. if (mesh && wm) {
  63428. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63429. tmat.multiplyToRef(wm, tmat);
  63430. }
  63431. else {
  63432. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63433. }
  63434. }
  63435. tmat.invert();
  63436. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63437. lm.m[12] = vec.x;
  63438. lm.m[13] = vec.y;
  63439. lm.m[14] = vec.z;
  63440. }
  63441. this.markAsDirty();
  63442. };
  63443. /**
  63444. * Set the absolute postion of the bone (world space).
  63445. * @param position The position to set the bone.
  63446. * @param mesh The mesh that this bone is attached to.
  63447. */
  63448. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63449. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63450. };
  63451. /**
  63452. * Set the scale of the bone on the x, y and z axes.
  63453. * @param x The scale of the bone on the x axis.
  63454. * @param x The scale of the bone on the y axis.
  63455. * @param z The scale of the bone on the z axis.
  63456. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63457. */
  63458. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63459. if (scaleChildren === void 0) { scaleChildren = false; }
  63460. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63461. if (!scaleChildren) {
  63462. this._negateScaleChildren.x = 1 / x;
  63463. this._negateScaleChildren.y = 1 / y;
  63464. this._negateScaleChildren.z = 1 / z;
  63465. }
  63466. this._syncScaleVector();
  63467. }
  63468. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63469. };
  63470. /**
  63471. * Scale the bone on the x, y and z axes.
  63472. * @param x The amount to scale the bone on the x axis.
  63473. * @param x The amount to scale the bone on the y axis.
  63474. * @param z The amount to scale the bone on the z axis.
  63475. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63476. */
  63477. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63478. if (scaleChildren === void 0) { scaleChildren = false; }
  63479. var locMat = this.getLocalMatrix();
  63480. var origLocMat = Bone._tmpMats[0];
  63481. origLocMat.copyFrom(locMat);
  63482. var origLocMatInv = Bone._tmpMats[1];
  63483. origLocMatInv.copyFrom(origLocMat);
  63484. origLocMatInv.invert();
  63485. var scaleMat = Bone._tmpMats[2];
  63486. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63487. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63488. this._scaleVector.x *= x;
  63489. this._scaleVector.y *= y;
  63490. this._scaleVector.z *= z;
  63491. locMat.multiplyToRef(origLocMatInv, locMat);
  63492. locMat.multiplyToRef(scaleMat, locMat);
  63493. locMat.multiplyToRef(origLocMat, locMat);
  63494. var parent = this.getParent();
  63495. if (parent) {
  63496. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63497. }
  63498. else {
  63499. this.getAbsoluteTransform().copyFrom(locMat);
  63500. }
  63501. var len = this.children.length;
  63502. scaleMat.invert();
  63503. for (var i = 0; i < len; i++) {
  63504. var child = this.children[i];
  63505. var cm = child.getLocalMatrix();
  63506. cm.multiplyToRef(scaleMat, cm);
  63507. var lm = child.getLocalMatrix();
  63508. lm.m[12] *= x;
  63509. lm.m[13] *= y;
  63510. lm.m[14] *= z;
  63511. }
  63512. this.computeAbsoluteTransforms();
  63513. if (scaleChildren) {
  63514. for (var i = 0; i < len; i++) {
  63515. this.children[i].scale(x, y, z, scaleChildren);
  63516. }
  63517. }
  63518. this.markAsDirty();
  63519. };
  63520. /**
  63521. * Set the yaw, pitch, and roll of the bone in local or world space.
  63522. * @param yaw The rotation of the bone on the y axis.
  63523. * @param pitch The rotation of the bone on the x axis.
  63524. * @param roll The rotation of the bone on the z axis.
  63525. * @param space The space that the axes of rotation are in.
  63526. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63527. */
  63528. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63529. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63530. var rotMat = Bone._tmpMats[0];
  63531. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63532. var rotMatInv = Bone._tmpMats[1];
  63533. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63534. rotMatInv.multiplyToRef(rotMat, rotMat);
  63535. this._rotateWithMatrix(rotMat, space, mesh);
  63536. };
  63537. /**
  63538. * Rotate the bone on an axis in local or world space.
  63539. * @param axis The axis to rotate the bone on.
  63540. * @param amount The amount to rotate the bone.
  63541. * @param space The space that the axis is in.
  63542. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63543. */
  63544. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63546. var rmat = Bone._tmpMats[0];
  63547. rmat.m[12] = 0;
  63548. rmat.m[13] = 0;
  63549. rmat.m[14] = 0;
  63550. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63551. this._rotateWithMatrix(rmat, space, mesh);
  63552. };
  63553. /**
  63554. * Set the rotation of the bone to a particular axis angle in local or world space.
  63555. * @param axis The axis to rotate the bone on.
  63556. * @param angle The angle that the bone should be rotated to.
  63557. * @param space The space that the axis is in.
  63558. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63559. */
  63560. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63561. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63562. var rotMat = Bone._tmpMats[0];
  63563. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63564. var rotMatInv = Bone._tmpMats[1];
  63565. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63566. rotMatInv.multiplyToRef(rotMat, rotMat);
  63567. this._rotateWithMatrix(rotMat, space, mesh);
  63568. };
  63569. /**
  63570. * Set the euler rotation of the bone in local of world space.
  63571. * @param rotation The euler rotation that the bone should be set to.
  63572. * @param space The space that the rotation is in.
  63573. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63574. */
  63575. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63577. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63578. };
  63579. /**
  63580. * Set the quaternion rotation of the bone in local of world space.
  63581. * @param quat The quaternion rotation that the bone should be set to.
  63582. * @param space The space that the rotation is in.
  63583. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63584. */
  63585. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63586. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63587. var rotMatInv = Bone._tmpMats[0];
  63588. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63589. var rotMat = Bone._tmpMats[1];
  63590. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63591. rotMatInv.multiplyToRef(rotMat, rotMat);
  63592. this._rotateWithMatrix(rotMat, space, mesh);
  63593. };
  63594. /**
  63595. * Set the rotation matrix of the bone in local of world space.
  63596. * @param rotMat The rotation matrix that the bone should be set to.
  63597. * @param space The space that the rotation is in.
  63598. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63599. */
  63600. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63601. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63602. var rotMatInv = Bone._tmpMats[0];
  63603. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63604. var rotMat2 = Bone._tmpMats[1];
  63605. rotMat2.copyFrom(rotMat);
  63606. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63607. this._rotateWithMatrix(rotMat2, space, mesh);
  63608. };
  63609. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63610. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63611. var lmat = this.getLocalMatrix();
  63612. var lx = lmat.m[12];
  63613. var ly = lmat.m[13];
  63614. var lz = lmat.m[14];
  63615. var parent = this.getParent();
  63616. var parentScale = Bone._tmpMats[3];
  63617. var parentScaleInv = Bone._tmpMats[4];
  63618. if (parent) {
  63619. if (space == BABYLON.Space.WORLD) {
  63620. if (mesh) {
  63621. parentScale.copyFrom(mesh.getWorldMatrix());
  63622. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63623. }
  63624. else {
  63625. parentScale.copyFrom(parent.getAbsoluteTransform());
  63626. }
  63627. }
  63628. else {
  63629. parentScale = parent._scaleMatrix;
  63630. }
  63631. parentScaleInv.copyFrom(parentScale);
  63632. parentScaleInv.invert();
  63633. lmat.multiplyToRef(parentScale, lmat);
  63634. lmat.multiplyToRef(rmat, lmat);
  63635. lmat.multiplyToRef(parentScaleInv, lmat);
  63636. }
  63637. else {
  63638. if (space == BABYLON.Space.WORLD && mesh) {
  63639. parentScale.copyFrom(mesh.getWorldMatrix());
  63640. parentScaleInv.copyFrom(parentScale);
  63641. parentScaleInv.invert();
  63642. lmat.multiplyToRef(parentScale, lmat);
  63643. lmat.multiplyToRef(rmat, lmat);
  63644. lmat.multiplyToRef(parentScaleInv, lmat);
  63645. }
  63646. else {
  63647. lmat.multiplyToRef(rmat, lmat);
  63648. }
  63649. }
  63650. lmat.m[12] = lx;
  63651. lmat.m[13] = ly;
  63652. lmat.m[14] = lz;
  63653. this.computeAbsoluteTransforms();
  63654. this.markAsDirty();
  63655. };
  63656. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63658. if (space == BABYLON.Space.WORLD) {
  63659. var scaleMatrix = Bone._tmpMats[2];
  63660. scaleMatrix.copyFrom(this._scaleMatrix);
  63661. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63662. if (mesh) {
  63663. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63664. var meshScale = Bone._tmpMats[3];
  63665. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63666. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63667. }
  63668. rotMatInv.invert();
  63669. scaleMatrix.m[0] *= this._scalingDeterminant;
  63670. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63671. }
  63672. else {
  63673. rotMatInv.copyFrom(this.getLocalMatrix());
  63674. rotMatInv.invert();
  63675. var scaleMatrix = Bone._tmpMats[2];
  63676. scaleMatrix.copyFrom(this._scaleMatrix);
  63677. if (this._parent) {
  63678. var pscaleMatrix = Bone._tmpMats[3];
  63679. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63680. pscaleMatrix.invert();
  63681. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63682. }
  63683. else {
  63684. scaleMatrix.m[0] *= this._scalingDeterminant;
  63685. }
  63686. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63687. }
  63688. };
  63689. /**
  63690. * Get the scale of the bone
  63691. * @returns the scale of the bone
  63692. */
  63693. Bone.prototype.getScale = function () {
  63694. return this._scaleVector.clone();
  63695. };
  63696. /**
  63697. * Copy the scale of the bone to a vector3.
  63698. * @param result The vector3 to copy the scale to
  63699. */
  63700. Bone.prototype.getScaleToRef = function (result) {
  63701. result.copyFrom(this._scaleVector);
  63702. };
  63703. /**
  63704. * Get the position of the bone in local or world space.
  63705. * @param space The space that the returned position is in.
  63706. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63707. * @returns The position of the bone
  63708. */
  63709. Bone.prototype.getPosition = function (space, mesh) {
  63710. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63711. if (mesh === void 0) { mesh = null; }
  63712. var pos = BABYLON.Vector3.Zero();
  63713. this.getPositionToRef(space, mesh, pos);
  63714. return pos;
  63715. };
  63716. /**
  63717. * Copy the position of the bone to a vector3 in local or world space.
  63718. * @param space The space that the returned position is in.
  63719. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63720. * @param result The vector3 to copy the position to.
  63721. */
  63722. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63724. if (space == BABYLON.Space.LOCAL) {
  63725. var lm = this.getLocalMatrix();
  63726. result.x = lm.m[12];
  63727. result.y = lm.m[13];
  63728. result.z = lm.m[14];
  63729. }
  63730. else {
  63731. var wm = null;
  63732. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63733. if (mesh) {
  63734. wm = mesh.getWorldMatrix();
  63735. }
  63736. this._skeleton.computeAbsoluteTransforms();
  63737. var tmat = Bone._tmpMats[0];
  63738. if (mesh && wm) {
  63739. tmat.copyFrom(this.getAbsoluteTransform());
  63740. tmat.multiplyToRef(wm, tmat);
  63741. }
  63742. else {
  63743. tmat = this.getAbsoluteTransform();
  63744. }
  63745. result.x = tmat.m[12];
  63746. result.y = tmat.m[13];
  63747. result.z = tmat.m[14];
  63748. }
  63749. };
  63750. /**
  63751. * Get the absolute position of the bone (world space).
  63752. * @param mesh The mesh that this bone is attached to.
  63753. * @returns The absolute position of the bone
  63754. */
  63755. Bone.prototype.getAbsolutePosition = function (mesh) {
  63756. if (mesh === void 0) { mesh = null; }
  63757. var pos = BABYLON.Vector3.Zero();
  63758. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63759. return pos;
  63760. };
  63761. /**
  63762. * Copy the absolute position of the bone (world space) to the result param.
  63763. * @param mesh The mesh that this bone is attached to.
  63764. * @param result The vector3 to copy the absolute position to.
  63765. */
  63766. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63767. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63768. };
  63769. /**
  63770. * Compute the absolute transforms of this bone and its children.
  63771. */
  63772. Bone.prototype.computeAbsoluteTransforms = function () {
  63773. if (this._parent) {
  63774. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63775. }
  63776. else {
  63777. this._absoluteTransform.copyFrom(this._localMatrix);
  63778. var poseMatrix = this._skeleton.getPoseMatrix();
  63779. if (poseMatrix) {
  63780. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63781. }
  63782. }
  63783. var children = this.children;
  63784. var len = children.length;
  63785. for (var i = 0; i < len; i++) {
  63786. children[i].computeAbsoluteTransforms();
  63787. }
  63788. };
  63789. Bone.prototype._syncScaleVector = function () {
  63790. var lm = this.getLocalMatrix();
  63791. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63792. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63793. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63794. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63795. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63796. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63797. this._scaleVector.x = xs * Math.sqrt(xsq);
  63798. this._scaleVector.y = ys * Math.sqrt(ysq);
  63799. this._scaleVector.z = zs * Math.sqrt(zsq);
  63800. if (this._parent) {
  63801. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63802. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63803. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63804. }
  63805. 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);
  63806. };
  63807. /**
  63808. * Get the world direction from an axis that is in the local space of the bone.
  63809. * @param localAxis The local direction that is used to compute the world direction.
  63810. * @param mesh The mesh that this bone is attached to.
  63811. * @returns The world direction
  63812. */
  63813. Bone.prototype.getDirection = function (localAxis, mesh) {
  63814. if (mesh === void 0) { mesh = null; }
  63815. var result = BABYLON.Vector3.Zero();
  63816. this.getDirectionToRef(localAxis, mesh, result);
  63817. return result;
  63818. };
  63819. /**
  63820. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63821. * @param localAxis The local direction that is used to compute the world direction.
  63822. * @param mesh The mesh that this bone is attached to.
  63823. * @param result The vector3 that the world direction will be copied to.
  63824. */
  63825. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63826. if (mesh === void 0) { mesh = null; }
  63827. var wm = null;
  63828. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63829. if (mesh) {
  63830. wm = mesh.getWorldMatrix();
  63831. }
  63832. this._skeleton.computeAbsoluteTransforms();
  63833. var mat = Bone._tmpMats[0];
  63834. mat.copyFrom(this.getAbsoluteTransform());
  63835. if (mesh && wm) {
  63836. mat.multiplyToRef(wm, mat);
  63837. }
  63838. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63839. result.normalize();
  63840. };
  63841. /**
  63842. * Get the euler rotation of the bone in local or world space.
  63843. * @param space The space that the rotation should be in.
  63844. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63845. * @returns The euler rotation
  63846. */
  63847. Bone.prototype.getRotation = function (space, mesh) {
  63848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63849. if (mesh === void 0) { mesh = null; }
  63850. var result = BABYLON.Vector3.Zero();
  63851. this.getRotationToRef(space, mesh, result);
  63852. return result;
  63853. };
  63854. /**
  63855. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63856. * @param space The space that the rotation should be in.
  63857. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63858. * @param result The vector3 that the rotation should be copied to.
  63859. */
  63860. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63861. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63862. if (mesh === void 0) { mesh = null; }
  63863. var quat = Bone._tmpQuat;
  63864. this.getRotationQuaternionToRef(space, mesh, quat);
  63865. quat.toEulerAnglesToRef(result);
  63866. };
  63867. /**
  63868. * Get the quaternion rotation of the bone in either local or world space.
  63869. * @param space The space that the rotation should be in.
  63870. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63871. * @returns The quaternion rotation
  63872. */
  63873. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63875. if (mesh === void 0) { mesh = null; }
  63876. var result = BABYLON.Quaternion.Identity();
  63877. this.getRotationQuaternionToRef(space, mesh, result);
  63878. return result;
  63879. };
  63880. /**
  63881. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63882. * @param space The space that the rotation should be in.
  63883. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63884. * @param result The quaternion that the rotation should be copied to.
  63885. */
  63886. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63888. if (mesh === void 0) { mesh = null; }
  63889. if (space == BABYLON.Space.LOCAL) {
  63890. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63891. }
  63892. else {
  63893. var mat = Bone._tmpMats[0];
  63894. var amat = this.getAbsoluteTransform();
  63895. if (mesh) {
  63896. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63897. }
  63898. else {
  63899. mat.copyFrom(amat);
  63900. }
  63901. mat.m[0] *= this._scalingDeterminant;
  63902. mat.m[1] *= this._scalingDeterminant;
  63903. mat.m[2] *= this._scalingDeterminant;
  63904. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63905. }
  63906. };
  63907. /**
  63908. * Get the rotation matrix of the bone in local or world space.
  63909. * @param space The space that the rotation should be in.
  63910. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63911. * @returns The rotation matrix
  63912. */
  63913. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63915. var result = BABYLON.Matrix.Identity();
  63916. this.getRotationMatrixToRef(space, mesh, result);
  63917. return result;
  63918. };
  63919. /**
  63920. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63921. * @param space The space that the rotation should be in.
  63922. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63923. * @param result The quaternion that the rotation should be copied to.
  63924. */
  63925. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63926. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63927. if (space == BABYLON.Space.LOCAL) {
  63928. this.getLocalMatrix().getRotationMatrixToRef(result);
  63929. }
  63930. else {
  63931. var mat = Bone._tmpMats[0];
  63932. var amat = this.getAbsoluteTransform();
  63933. if (mesh) {
  63934. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63935. }
  63936. else {
  63937. mat.copyFrom(amat);
  63938. }
  63939. mat.m[0] *= this._scalingDeterminant;
  63940. mat.m[1] *= this._scalingDeterminant;
  63941. mat.m[2] *= this._scalingDeterminant;
  63942. mat.getRotationMatrixToRef(result);
  63943. }
  63944. };
  63945. /**
  63946. * Get the world position of a point that is in the local space of the bone.
  63947. * @param position The local position
  63948. * @param mesh The mesh that this bone is attached to.
  63949. * @returns The world position
  63950. */
  63951. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63952. if (mesh === void 0) { mesh = null; }
  63953. var result = BABYLON.Vector3.Zero();
  63954. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63955. return result;
  63956. };
  63957. /**
  63958. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63959. * @param position The local position
  63960. * @param mesh The mesh that this bone is attached to.
  63961. * @param result The vector3 that the world position should be copied to.
  63962. */
  63963. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63964. if (mesh === void 0) { mesh = null; }
  63965. var wm = null;
  63966. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63967. if (mesh) {
  63968. wm = mesh.getWorldMatrix();
  63969. }
  63970. this._skeleton.computeAbsoluteTransforms();
  63971. var tmat = Bone._tmpMats[0];
  63972. if (mesh && wm) {
  63973. tmat.copyFrom(this.getAbsoluteTransform());
  63974. tmat.multiplyToRef(wm, tmat);
  63975. }
  63976. else {
  63977. tmat = this.getAbsoluteTransform();
  63978. }
  63979. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63980. };
  63981. /**
  63982. * Get the local position of a point that is in world space.
  63983. * @param position The world position
  63984. * @param mesh The mesh that this bone is attached to.
  63985. * @returns The local position
  63986. */
  63987. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  63988. if (mesh === void 0) { mesh = null; }
  63989. var result = BABYLON.Vector3.Zero();
  63990. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  63991. return result;
  63992. };
  63993. /**
  63994. * Get the local position of a point that is in world space and copy it to the result param.
  63995. * @param position The world position
  63996. * @param mesh The mesh that this bone is attached to.
  63997. * @param result The vector3 that the local position should be copied to.
  63998. */
  63999. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64000. if (mesh === void 0) { mesh = null; }
  64001. var wm = null;
  64002. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64003. if (mesh) {
  64004. wm = mesh.getWorldMatrix();
  64005. }
  64006. this._skeleton.computeAbsoluteTransforms();
  64007. var tmat = Bone._tmpMats[0];
  64008. tmat.copyFrom(this.getAbsoluteTransform());
  64009. if (mesh && wm) {
  64010. tmat.multiplyToRef(wm, tmat);
  64011. }
  64012. tmat.invert();
  64013. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64014. };
  64015. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64016. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64017. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64018. return Bone;
  64019. }(BABYLON.Node));
  64020. BABYLON.Bone = Bone;
  64021. })(BABYLON || (BABYLON = {}));
  64022. //# sourceMappingURL=babylon.bone.js.map
  64023. var BABYLON;
  64024. (function (BABYLON) {
  64025. var BoneIKController = /** @class */ (function () {
  64026. function BoneIKController(mesh, bone, options) {
  64027. this.targetPosition = BABYLON.Vector3.Zero();
  64028. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64029. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64030. this.poleAngle = 0;
  64031. this.slerpAmount = 1;
  64032. this._bone1Quat = BABYLON.Quaternion.Identity();
  64033. this._bone1Mat = BABYLON.Matrix.Identity();
  64034. this._bone2Ang = Math.PI;
  64035. this._maxAngle = Math.PI;
  64036. this._rightHandedSystem = false;
  64037. this._bendAxis = BABYLON.Vector3.Right();
  64038. this._slerping = false;
  64039. this._adjustRoll = 0;
  64040. this._bone2 = bone;
  64041. this._bone1 = bone.getParent();
  64042. if (!this._bone1) {
  64043. return;
  64044. }
  64045. this.mesh = mesh;
  64046. var bonePos = bone.getPosition();
  64047. if (bone.getAbsoluteTransform().determinant() > 0) {
  64048. this._rightHandedSystem = true;
  64049. this._bendAxis.x = 0;
  64050. this._bendAxis.y = 0;
  64051. this._bendAxis.z = -1;
  64052. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64053. this._adjustRoll = Math.PI * .5;
  64054. this._bendAxis.z = 1;
  64055. }
  64056. }
  64057. if (this._bone1.length) {
  64058. var boneScale1 = this._bone1.getScale();
  64059. var boneScale2 = this._bone2.getScale();
  64060. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64061. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64062. }
  64063. else if (this._bone1.children[0]) {
  64064. mesh.computeWorldMatrix(true);
  64065. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64066. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64067. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64068. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64069. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64070. }
  64071. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64072. this.maxAngle = Math.PI;
  64073. if (options) {
  64074. if (options.targetMesh) {
  64075. this.targetMesh = options.targetMesh;
  64076. this.targetMesh.computeWorldMatrix(true);
  64077. }
  64078. if (options.poleTargetMesh) {
  64079. this.poleTargetMesh = options.poleTargetMesh;
  64080. this.poleTargetMesh.computeWorldMatrix(true);
  64081. }
  64082. else if (options.poleTargetBone) {
  64083. this.poleTargetBone = options.poleTargetBone;
  64084. }
  64085. else if (this._bone1.getParent()) {
  64086. this.poleTargetBone = this._bone1.getParent();
  64087. }
  64088. if (options.poleTargetLocalOffset) {
  64089. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64090. }
  64091. if (options.poleAngle) {
  64092. this.poleAngle = options.poleAngle;
  64093. }
  64094. if (options.bendAxis) {
  64095. this._bendAxis.copyFrom(options.bendAxis);
  64096. }
  64097. if (options.maxAngle) {
  64098. this.maxAngle = options.maxAngle;
  64099. }
  64100. if (options.slerpAmount) {
  64101. this.slerpAmount = options.slerpAmount;
  64102. }
  64103. }
  64104. }
  64105. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64106. get: function () {
  64107. return this._maxAngle;
  64108. },
  64109. set: function (value) {
  64110. this._setMaxAngle(value);
  64111. },
  64112. enumerable: true,
  64113. configurable: true
  64114. });
  64115. BoneIKController.prototype._setMaxAngle = function (ang) {
  64116. if (ang < 0) {
  64117. ang = 0;
  64118. }
  64119. if (ang > Math.PI || ang == undefined) {
  64120. ang = Math.PI;
  64121. }
  64122. this._maxAngle = ang;
  64123. var a = this._bone1Length;
  64124. var b = this._bone2Length;
  64125. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64126. };
  64127. BoneIKController.prototype.update = function () {
  64128. var bone1 = this._bone1;
  64129. if (!bone1) {
  64130. return;
  64131. }
  64132. var target = this.targetPosition;
  64133. var poleTarget = this.poleTargetPosition;
  64134. var mat1 = BoneIKController._tmpMats[0];
  64135. var mat2 = BoneIKController._tmpMats[1];
  64136. if (this.targetMesh) {
  64137. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64138. }
  64139. if (this.poleTargetBone) {
  64140. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64141. }
  64142. else if (this.poleTargetMesh) {
  64143. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64144. }
  64145. var bonePos = BoneIKController._tmpVecs[0];
  64146. var zaxis = BoneIKController._tmpVecs[1];
  64147. var xaxis = BoneIKController._tmpVecs[2];
  64148. var yaxis = BoneIKController._tmpVecs[3];
  64149. var upAxis = BoneIKController._tmpVecs[4];
  64150. var _tmpQuat = BoneIKController._tmpQuat;
  64151. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64152. poleTarget.subtractToRef(bonePos, upAxis);
  64153. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64154. upAxis.y = 1;
  64155. }
  64156. else {
  64157. upAxis.normalize();
  64158. }
  64159. target.subtractToRef(bonePos, yaxis);
  64160. yaxis.normalize();
  64161. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64162. zaxis.normalize();
  64163. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64164. xaxis.normalize();
  64165. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64166. var a = this._bone1Length;
  64167. var b = this._bone2Length;
  64168. var c = BABYLON.Vector3.Distance(bonePos, target);
  64169. if (this._maxReach > 0) {
  64170. c = Math.min(this._maxReach, c);
  64171. }
  64172. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64173. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64174. if (acosa > 1) {
  64175. acosa = 1;
  64176. }
  64177. if (acosb > 1) {
  64178. acosb = 1;
  64179. }
  64180. if (acosa < -1) {
  64181. acosa = -1;
  64182. }
  64183. if (acosb < -1) {
  64184. acosb = -1;
  64185. }
  64186. var angA = Math.acos(acosa);
  64187. var angB = Math.acos(acosb);
  64188. var angC = -angA - angB;
  64189. if (this._rightHandedSystem) {
  64190. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64191. mat2.multiplyToRef(mat1, mat1);
  64192. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64193. mat2.multiplyToRef(mat1, mat1);
  64194. }
  64195. else {
  64196. var _tmpVec = BoneIKController._tmpVecs[5];
  64197. _tmpVec.copyFrom(this._bendAxis);
  64198. _tmpVec.x *= -1;
  64199. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64200. mat2.multiplyToRef(mat1, mat1);
  64201. }
  64202. if (this.poleAngle) {
  64203. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64204. mat1.multiplyToRef(mat2, mat1);
  64205. }
  64206. if (this._bone1) {
  64207. if (this.slerpAmount < 1) {
  64208. if (!this._slerping) {
  64209. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64210. }
  64211. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64212. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64213. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64214. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64215. this._slerping = true;
  64216. }
  64217. else {
  64218. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64219. this._bone1Mat.copyFrom(mat1);
  64220. this._slerping = false;
  64221. }
  64222. }
  64223. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64224. this._bone2Ang = angC;
  64225. };
  64226. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64227. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64228. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64229. return BoneIKController;
  64230. }());
  64231. BABYLON.BoneIKController = BoneIKController;
  64232. })(BABYLON || (BABYLON = {}));
  64233. //# sourceMappingURL=babylon.boneIKController.js.map
  64234. var BABYLON;
  64235. (function (BABYLON) {
  64236. var BoneLookController = /** @class */ (function () {
  64237. /**
  64238. * Create a BoneLookController
  64239. * @param mesh the mesh that the bone belongs to
  64240. * @param bone the bone that will be looking to the target
  64241. * @param target the target Vector3 to look at
  64242. * @param settings optional settings:
  64243. * - maxYaw: the maximum angle the bone will yaw to
  64244. * - minYaw: the minimum angle the bone will yaw to
  64245. * - maxPitch: the maximum angle the bone will pitch to
  64246. * - minPitch: the minimum angle the bone will yaw to
  64247. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64248. * - upAxis: the up axis of the coordinate system
  64249. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64250. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64251. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64252. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64253. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64254. * - adjustRoll: used to make an adjustment to the roll of the bone
  64255. **/
  64256. function BoneLookController(mesh, bone, target, options) {
  64257. /**
  64258. * The up axis of the coordinate system that is used when the bone is rotated.
  64259. */
  64260. this.upAxis = BABYLON.Vector3.Up();
  64261. /**
  64262. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64263. */
  64264. this.upAxisSpace = BABYLON.Space.LOCAL;
  64265. /**
  64266. * Used to make an adjustment to the yaw of the bone.
  64267. */
  64268. this.adjustYaw = 0;
  64269. /**
  64270. * Used to make an adjustment to the pitch of the bone.
  64271. */
  64272. this.adjustPitch = 0;
  64273. /**
  64274. * Used to make an adjustment to the roll of the bone.
  64275. */
  64276. this.adjustRoll = 0;
  64277. /**
  64278. * 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).
  64279. */
  64280. this.slerpAmount = 1;
  64281. this._boneQuat = BABYLON.Quaternion.Identity();
  64282. this._slerping = false;
  64283. this._firstFrameSkipped = false;
  64284. this._fowardAxis = BABYLON.Vector3.Forward();
  64285. this.mesh = mesh;
  64286. this.bone = bone;
  64287. this.target = target;
  64288. if (options) {
  64289. if (options.adjustYaw) {
  64290. this.adjustYaw = options.adjustYaw;
  64291. }
  64292. if (options.adjustPitch) {
  64293. this.adjustPitch = options.adjustPitch;
  64294. }
  64295. if (options.adjustRoll) {
  64296. this.adjustRoll = options.adjustRoll;
  64297. }
  64298. if (options.maxYaw != null) {
  64299. this.maxYaw = options.maxYaw;
  64300. }
  64301. else {
  64302. this.maxYaw = Math.PI;
  64303. }
  64304. if (options.minYaw != null) {
  64305. this.minYaw = options.minYaw;
  64306. }
  64307. else {
  64308. this.minYaw = -Math.PI;
  64309. }
  64310. if (options.maxPitch != null) {
  64311. this.maxPitch = options.maxPitch;
  64312. }
  64313. else {
  64314. this.maxPitch = Math.PI;
  64315. }
  64316. if (options.minPitch != null) {
  64317. this.minPitch = options.minPitch;
  64318. }
  64319. else {
  64320. this.minPitch = -Math.PI;
  64321. }
  64322. if (options.slerpAmount != null) {
  64323. this.slerpAmount = options.slerpAmount;
  64324. }
  64325. if (options.upAxis != null) {
  64326. this.upAxis = options.upAxis;
  64327. }
  64328. if (options.upAxisSpace != null) {
  64329. this.upAxisSpace = options.upAxisSpace;
  64330. }
  64331. if (options.yawAxis != null || options.pitchAxis != null) {
  64332. var newYawAxis = BABYLON.Axis.Y;
  64333. var newPitchAxis = BABYLON.Axis.X;
  64334. if (options.yawAxis != null) {
  64335. newYawAxis = options.yawAxis.clone();
  64336. newYawAxis.normalize();
  64337. }
  64338. if (options.pitchAxis != null) {
  64339. newPitchAxis = options.pitchAxis.clone();
  64340. newPitchAxis.normalize();
  64341. }
  64342. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64343. this._transformYawPitch = BABYLON.Matrix.Identity();
  64344. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64345. this._transformYawPitchInv = this._transformYawPitch.clone();
  64346. this._transformYawPitch.invert();
  64347. }
  64348. }
  64349. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64350. this.upAxisSpace = BABYLON.Space.LOCAL;
  64351. }
  64352. }
  64353. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64354. /**
  64355. * Get/set the minimum yaw angle that the bone can look to.
  64356. */
  64357. get: function () {
  64358. return this._minYaw;
  64359. },
  64360. set: function (value) {
  64361. this._minYaw = value;
  64362. this._minYawSin = Math.sin(value);
  64363. this._minYawCos = Math.cos(value);
  64364. if (this._maxYaw != null) {
  64365. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64366. this._yawRange = this._maxYaw - this._minYaw;
  64367. }
  64368. },
  64369. enumerable: true,
  64370. configurable: true
  64371. });
  64372. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64373. /**
  64374. * Get/set the maximum yaw angle that the bone can look to.
  64375. */
  64376. get: function () {
  64377. return this._maxYaw;
  64378. },
  64379. set: function (value) {
  64380. this._maxYaw = value;
  64381. this._maxYawSin = Math.sin(value);
  64382. this._maxYawCos = Math.cos(value);
  64383. if (this._minYaw != null) {
  64384. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64385. this._yawRange = this._maxYaw - this._minYaw;
  64386. }
  64387. },
  64388. enumerable: true,
  64389. configurable: true
  64390. });
  64391. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64392. /**
  64393. * Get/set the minimum pitch angle that the bone can look to.
  64394. */
  64395. get: function () {
  64396. return this._minPitch;
  64397. },
  64398. set: function (value) {
  64399. this._minPitch = value;
  64400. this._minPitchTan = Math.tan(value);
  64401. },
  64402. enumerable: true,
  64403. configurable: true
  64404. });
  64405. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64406. /**
  64407. * Get/set the maximum pitch angle that the bone can look to.
  64408. */
  64409. get: function () {
  64410. return this._maxPitch;
  64411. },
  64412. set: function (value) {
  64413. this._maxPitch = value;
  64414. this._maxPitchTan = Math.tan(value);
  64415. },
  64416. enumerable: true,
  64417. configurable: true
  64418. });
  64419. /**
  64420. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64421. */
  64422. BoneLookController.prototype.update = function () {
  64423. //skip the first frame when slerping so that the mesh rotation is correct
  64424. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64425. this._firstFrameSkipped = true;
  64426. return;
  64427. }
  64428. var bone = this.bone;
  64429. var bonePos = BoneLookController._tmpVecs[0];
  64430. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64431. var target = this.target;
  64432. var _tmpMat1 = BoneLookController._tmpMats[0];
  64433. var _tmpMat2 = BoneLookController._tmpMats[1];
  64434. var mesh = this.mesh;
  64435. var parentBone = bone.getParent();
  64436. var upAxis = BoneLookController._tmpVecs[1];
  64437. upAxis.copyFrom(this.upAxis);
  64438. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64439. if (this._transformYawPitch) {
  64440. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64441. }
  64442. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64443. }
  64444. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64445. mesh.getDirectionToRef(upAxis, upAxis);
  64446. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64447. upAxis.normalize();
  64448. }
  64449. }
  64450. var checkYaw = false;
  64451. var checkPitch = false;
  64452. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64453. checkYaw = true;
  64454. }
  64455. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64456. checkPitch = true;
  64457. }
  64458. if (checkYaw || checkPitch) {
  64459. var spaceMat = BoneLookController._tmpMats[2];
  64460. var spaceMatInv = BoneLookController._tmpMats[3];
  64461. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64462. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64463. }
  64464. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64465. spaceMat.copyFrom(mesh.getWorldMatrix());
  64466. }
  64467. else {
  64468. var forwardAxis = BoneLookController._tmpVecs[2];
  64469. forwardAxis.copyFrom(this._fowardAxis);
  64470. if (this._transformYawPitch) {
  64471. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64472. }
  64473. if (parentBone) {
  64474. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64475. }
  64476. else {
  64477. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64478. }
  64479. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64480. rightAxis.normalize();
  64481. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64482. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64483. }
  64484. spaceMat.invertToRef(spaceMatInv);
  64485. var xzlen = null;
  64486. if (checkPitch) {
  64487. var localTarget = BoneLookController._tmpVecs[3];
  64488. target.subtractToRef(bonePos, localTarget);
  64489. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64490. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64491. var pitch = Math.atan2(localTarget.y, xzlen);
  64492. var newPitch = pitch;
  64493. if (pitch > this._maxPitch) {
  64494. localTarget.y = this._maxPitchTan * xzlen;
  64495. newPitch = this._maxPitch;
  64496. }
  64497. else if (pitch < this._minPitch) {
  64498. localTarget.y = this._minPitchTan * xzlen;
  64499. newPitch = this._minPitch;
  64500. }
  64501. if (pitch != newPitch) {
  64502. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64503. localTarget.addInPlace(bonePos);
  64504. target = localTarget;
  64505. }
  64506. }
  64507. if (checkYaw) {
  64508. var localTarget = BoneLookController._tmpVecs[4];
  64509. target.subtractToRef(bonePos, localTarget);
  64510. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64511. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64512. var newYaw = yaw;
  64513. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64514. if (xzlen == null) {
  64515. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64516. }
  64517. if (this._yawRange > Math.PI) {
  64518. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64519. localTarget.z = this._maxYawCos * xzlen;
  64520. localTarget.x = this._maxYawSin * xzlen;
  64521. newYaw = this._maxYaw;
  64522. }
  64523. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64524. localTarget.z = this._minYawCos * xzlen;
  64525. localTarget.x = this._minYawSin * xzlen;
  64526. newYaw = this._minYaw;
  64527. }
  64528. }
  64529. else {
  64530. if (yaw > this._maxYaw) {
  64531. localTarget.z = this._maxYawCos * xzlen;
  64532. localTarget.x = this._maxYawSin * xzlen;
  64533. newYaw = this._maxYaw;
  64534. }
  64535. else if (yaw < this._minYaw) {
  64536. localTarget.z = this._minYawCos * xzlen;
  64537. localTarget.x = this._minYawSin * xzlen;
  64538. newYaw = this._minYaw;
  64539. }
  64540. }
  64541. }
  64542. if (this._slerping && this._yawRange > Math.PI) {
  64543. //are we going to be crossing into the min/max region?
  64544. var boneFwd = BoneLookController._tmpVecs[8];
  64545. boneFwd.copyFrom(BABYLON.Axis.Z);
  64546. if (this._transformYawPitch) {
  64547. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64548. }
  64549. var boneRotMat = BoneLookController._tmpMats[4];
  64550. this._boneQuat.toRotationMatrix(boneRotMat);
  64551. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64552. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64553. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64554. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64555. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64556. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64557. if (angBtwTar > angBtwMidYaw) {
  64558. if (xzlen == null) {
  64559. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64560. }
  64561. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64562. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64563. if (angBtwMin < angBtwMax) {
  64564. newYaw = boneYaw + Math.PI * .75;
  64565. localTarget.z = Math.cos(newYaw) * xzlen;
  64566. localTarget.x = Math.sin(newYaw) * xzlen;
  64567. }
  64568. else {
  64569. newYaw = boneYaw - Math.PI * .75;
  64570. localTarget.z = Math.cos(newYaw) * xzlen;
  64571. localTarget.x = Math.sin(newYaw) * xzlen;
  64572. }
  64573. }
  64574. }
  64575. if (yaw != newYaw) {
  64576. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64577. localTarget.addInPlace(bonePos);
  64578. target = localTarget;
  64579. }
  64580. }
  64581. }
  64582. var zaxis = BoneLookController._tmpVecs[5];
  64583. var xaxis = BoneLookController._tmpVecs[6];
  64584. var yaxis = BoneLookController._tmpVecs[7];
  64585. var _tmpQuat = BoneLookController._tmpQuat;
  64586. target.subtractToRef(bonePos, zaxis);
  64587. zaxis.normalize();
  64588. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64589. xaxis.normalize();
  64590. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64591. yaxis.normalize();
  64592. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64593. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64594. return;
  64595. }
  64596. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64597. return;
  64598. }
  64599. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64600. return;
  64601. }
  64602. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64603. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64604. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64605. }
  64606. if (this.slerpAmount < 1) {
  64607. if (!this._slerping) {
  64608. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64609. }
  64610. if (this._transformYawPitch) {
  64611. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64612. }
  64613. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64614. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64615. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64616. this._slerping = true;
  64617. }
  64618. else {
  64619. if (this._transformYawPitch) {
  64620. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64621. }
  64622. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64623. this._slerping = false;
  64624. }
  64625. };
  64626. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64627. var angDiff = ang2 - ang1;
  64628. angDiff %= Math.PI * 2;
  64629. if (angDiff > Math.PI) {
  64630. angDiff -= Math.PI * 2;
  64631. }
  64632. else if (angDiff < -Math.PI) {
  64633. angDiff += Math.PI * 2;
  64634. }
  64635. return angDiff;
  64636. };
  64637. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64638. ang1 %= (2 * Math.PI);
  64639. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64640. ang2 %= (2 * Math.PI);
  64641. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64642. var ab = 0;
  64643. if (ang1 < ang2) {
  64644. ab = ang2 - ang1;
  64645. }
  64646. else {
  64647. ab = ang1 - ang2;
  64648. }
  64649. if (ab > Math.PI) {
  64650. ab = Math.PI * 2 - ab;
  64651. }
  64652. return ab;
  64653. };
  64654. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64655. ang %= (2 * Math.PI);
  64656. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64657. ang1 %= (2 * Math.PI);
  64658. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64659. ang2 %= (2 * Math.PI);
  64660. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64661. if (ang1 < ang2) {
  64662. if (ang > ang1 && ang < ang2) {
  64663. return true;
  64664. }
  64665. }
  64666. else {
  64667. if (ang > ang2 && ang < ang1) {
  64668. return true;
  64669. }
  64670. }
  64671. return false;
  64672. };
  64673. 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()];
  64674. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64675. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64676. return BoneLookController;
  64677. }());
  64678. BABYLON.BoneLookController = BoneLookController;
  64679. })(BABYLON || (BABYLON = {}));
  64680. //# sourceMappingURL=babylon.boneLookController.js.map
  64681. var BABYLON;
  64682. (function (BABYLON) {
  64683. var Skeleton = /** @class */ (function () {
  64684. function Skeleton(name, id, scene) {
  64685. this.name = name;
  64686. this.id = id;
  64687. this.bones = new Array();
  64688. this.needInitialSkinMatrix = false;
  64689. this._isDirty = true;
  64690. this._meshesWithPoseMatrix = new Array();
  64691. this._identity = BABYLON.Matrix.Identity();
  64692. this._ranges = {};
  64693. this._lastAbsoluteTransformsUpdateId = -1;
  64694. // Events
  64695. /**
  64696. * An event triggered before computing the skeleton's matrices
  64697. * @type {BABYLON.Observable}
  64698. */
  64699. this.onBeforeComputeObservable = new BABYLON.Observable();
  64700. this.bones = [];
  64701. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64702. scene.skeletons.push(this);
  64703. //make sure it will recalculate the matrix next time prepare is called.
  64704. this._isDirty = true;
  64705. }
  64706. // Members
  64707. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64708. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64709. return mesh._bonesTransformMatrices;
  64710. }
  64711. if (!this._transformMatrices) {
  64712. this.prepare();
  64713. }
  64714. return this._transformMatrices;
  64715. };
  64716. Skeleton.prototype.getScene = function () {
  64717. return this._scene;
  64718. };
  64719. // Methods
  64720. /**
  64721. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64722. */
  64723. Skeleton.prototype.toString = function (fullDetails) {
  64724. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64725. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64726. if (fullDetails) {
  64727. ret += ", Ranges: {";
  64728. var first = true;
  64729. for (var name_1 in this._ranges) {
  64730. if (first) {
  64731. ret += ", ";
  64732. first = false;
  64733. }
  64734. ret += name_1;
  64735. }
  64736. ret += "}";
  64737. }
  64738. return ret;
  64739. };
  64740. /**
  64741. * Get bone's index searching by name
  64742. * @param {string} name is bone's name to search for
  64743. * @return {number} Indice of the bone. Returns -1 if not found
  64744. */
  64745. Skeleton.prototype.getBoneIndexByName = function (name) {
  64746. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64747. if (this.bones[boneIndex].name === name) {
  64748. return boneIndex;
  64749. }
  64750. }
  64751. return -1;
  64752. };
  64753. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64754. // check name not already in use
  64755. if (!this._ranges[name]) {
  64756. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64757. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64758. if (this.bones[i].animations[0]) {
  64759. this.bones[i].animations[0].createRange(name, from, to);
  64760. }
  64761. }
  64762. }
  64763. };
  64764. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64765. if (deleteFrames === void 0) { deleteFrames = true; }
  64766. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64767. if (this.bones[i].animations[0]) {
  64768. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64769. }
  64770. }
  64771. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64772. };
  64773. Skeleton.prototype.getAnimationRange = function (name) {
  64774. return this._ranges[name];
  64775. };
  64776. /**
  64777. * Returns as an Array, all AnimationRanges defined on this skeleton
  64778. */
  64779. Skeleton.prototype.getAnimationRanges = function () {
  64780. var animationRanges = [];
  64781. var name;
  64782. var i = 0;
  64783. for (name in this._ranges) {
  64784. animationRanges[i] = this._ranges[name];
  64785. i++;
  64786. }
  64787. return animationRanges;
  64788. };
  64789. /**
  64790. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64791. */
  64792. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64793. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64794. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64795. return false;
  64796. }
  64797. var ret = true;
  64798. var frameOffset = this._getHighestAnimationFrame() + 1;
  64799. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64800. var boneDict = {};
  64801. var sourceBones = source.bones;
  64802. var nBones;
  64803. var i;
  64804. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64805. boneDict[sourceBones[i].name] = sourceBones[i];
  64806. }
  64807. if (this.bones.length !== sourceBones.length) {
  64808. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64809. ret = false;
  64810. }
  64811. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64812. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64813. var boneName = this.bones[i].name;
  64814. var sourceBone = boneDict[boneName];
  64815. if (sourceBone) {
  64816. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64817. }
  64818. else {
  64819. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64820. ret = false;
  64821. }
  64822. }
  64823. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64824. var range = source.getAnimationRange(name);
  64825. if (range) {
  64826. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64827. }
  64828. return ret;
  64829. };
  64830. Skeleton.prototype.returnToRest = function () {
  64831. for (var index = 0; index < this.bones.length; index++) {
  64832. this.bones[index].returnToRest();
  64833. }
  64834. };
  64835. Skeleton.prototype._getHighestAnimationFrame = function () {
  64836. var ret = 0;
  64837. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64838. if (this.bones[i].animations[0]) {
  64839. var highest = this.bones[i].animations[0].getHighestFrame();
  64840. if (ret < highest) {
  64841. ret = highest;
  64842. }
  64843. }
  64844. }
  64845. return ret;
  64846. };
  64847. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64848. var range = this.getAnimationRange(name);
  64849. if (!range) {
  64850. return null;
  64851. }
  64852. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64853. };
  64854. Skeleton.prototype._markAsDirty = function () {
  64855. this._isDirty = true;
  64856. };
  64857. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64858. this._meshesWithPoseMatrix.push(mesh);
  64859. };
  64860. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64861. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64862. if (index > -1) {
  64863. this._meshesWithPoseMatrix.splice(index, 1);
  64864. }
  64865. };
  64866. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64867. this.onBeforeComputeObservable.notifyObservers(this);
  64868. for (var index = 0; index < this.bones.length; index++) {
  64869. var bone = this.bones[index];
  64870. var parentBone = bone.getParent();
  64871. if (parentBone) {
  64872. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64873. }
  64874. else {
  64875. if (initialSkinMatrix) {
  64876. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64877. }
  64878. else {
  64879. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64880. }
  64881. }
  64882. if (bone._index !== -1) {
  64883. var mappedIndex = bone._index === null ? index : bone._index;
  64884. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64885. }
  64886. }
  64887. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64888. };
  64889. Skeleton.prototype.prepare = function () {
  64890. if (!this._isDirty) {
  64891. return;
  64892. }
  64893. if (this.needInitialSkinMatrix) {
  64894. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64895. var mesh = this._meshesWithPoseMatrix[index];
  64896. var poseMatrix = mesh.getPoseMatrix();
  64897. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64898. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64899. }
  64900. if (this._synchronizedWithMesh !== mesh) {
  64901. this._synchronizedWithMesh = mesh;
  64902. // Prepare bones
  64903. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64904. var bone = this.bones[boneIndex];
  64905. if (!bone.getParent()) {
  64906. var matrix = bone.getBaseMatrix();
  64907. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64908. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64909. }
  64910. }
  64911. }
  64912. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64913. }
  64914. }
  64915. else {
  64916. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64917. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64918. }
  64919. this._computeTransformMatrices(this._transformMatrices, null);
  64920. }
  64921. this._isDirty = false;
  64922. this._scene._activeBones.addCount(this.bones.length, false);
  64923. };
  64924. Skeleton.prototype.getAnimatables = function () {
  64925. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64926. this._animatables = [];
  64927. for (var index = 0; index < this.bones.length; index++) {
  64928. this._animatables.push(this.bones[index]);
  64929. }
  64930. }
  64931. return this._animatables;
  64932. };
  64933. Skeleton.prototype.clone = function (name, id) {
  64934. var result = new Skeleton(name, id || name, this._scene);
  64935. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64936. for (var index = 0; index < this.bones.length; index++) {
  64937. var source = this.bones[index];
  64938. var parentBone = null;
  64939. var parent_1 = source.getParent();
  64940. if (parent_1) {
  64941. var parentIndex = this.bones.indexOf(parent_1);
  64942. parentBone = result.bones[parentIndex];
  64943. }
  64944. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64945. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64946. }
  64947. if (this._ranges) {
  64948. result._ranges = {};
  64949. for (var rangeName in this._ranges) {
  64950. var range = this._ranges[rangeName];
  64951. if (range) {
  64952. result._ranges[rangeName] = range.clone();
  64953. }
  64954. }
  64955. }
  64956. this._isDirty = true;
  64957. return result;
  64958. };
  64959. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64960. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64961. this.bones.forEach(function (bone) {
  64962. bone.animations.forEach(function (animation) {
  64963. animation.enableBlending = true;
  64964. animation.blendingSpeed = blendingSpeed;
  64965. });
  64966. });
  64967. };
  64968. Skeleton.prototype.dispose = function () {
  64969. this._meshesWithPoseMatrix = [];
  64970. // Animations
  64971. this.getScene().stopAnimation(this);
  64972. // Remove from scene
  64973. this.getScene().removeSkeleton(this);
  64974. };
  64975. Skeleton.prototype.serialize = function () {
  64976. var serializationObject = {};
  64977. serializationObject.name = this.name;
  64978. serializationObject.id = this.id;
  64979. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  64980. serializationObject.bones = [];
  64981. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64982. for (var index = 0; index < this.bones.length; index++) {
  64983. var bone = this.bones[index];
  64984. var parent_2 = bone.getParent();
  64985. var serializedBone = {
  64986. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  64987. name: bone.name,
  64988. matrix: bone.getBaseMatrix().toArray(),
  64989. rest: bone.getRestPose().toArray()
  64990. };
  64991. serializationObject.bones.push(serializedBone);
  64992. if (bone.length) {
  64993. serializedBone.length = bone.length;
  64994. }
  64995. if (bone.animations && bone.animations.length > 0) {
  64996. serializedBone.animation = bone.animations[0].serialize();
  64997. }
  64998. serializationObject.ranges = [];
  64999. for (var name in this._ranges) {
  65000. var source = this._ranges[name];
  65001. if (!source) {
  65002. continue;
  65003. }
  65004. var range = {};
  65005. range.name = name;
  65006. range.from = source.from;
  65007. range.to = source.to;
  65008. serializationObject.ranges.push(range);
  65009. }
  65010. }
  65011. return serializationObject;
  65012. };
  65013. Skeleton.Parse = function (parsedSkeleton, scene) {
  65014. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65015. if (parsedSkeleton.dimensionsAtRest) {
  65016. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65017. }
  65018. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65019. var index;
  65020. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65021. var parsedBone = parsedSkeleton.bones[index];
  65022. var parentBone = null;
  65023. if (parsedBone.parentBoneIndex > -1) {
  65024. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65025. }
  65026. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65027. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65028. if (parsedBone.length) {
  65029. bone.length = parsedBone.length;
  65030. }
  65031. if (parsedBone.animation) {
  65032. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65033. }
  65034. }
  65035. // placed after bones, so createAnimationRange can cascade down
  65036. if (parsedSkeleton.ranges) {
  65037. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65038. var data = parsedSkeleton.ranges[index];
  65039. skeleton.createAnimationRange(data.name, data.from, data.to);
  65040. }
  65041. }
  65042. return skeleton;
  65043. };
  65044. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65045. if (forceUpdate === void 0) { forceUpdate = false; }
  65046. var renderId = this._scene.getRenderId();
  65047. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65048. this.bones[0].computeAbsoluteTransforms();
  65049. this._lastAbsoluteTransformsUpdateId = renderId;
  65050. }
  65051. };
  65052. Skeleton.prototype.getPoseMatrix = function () {
  65053. var poseMatrix = null;
  65054. if (this._meshesWithPoseMatrix.length > 0) {
  65055. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65056. }
  65057. return poseMatrix;
  65058. };
  65059. Skeleton.prototype.sortBones = function () {
  65060. var bones = new Array();
  65061. var visited = new Array(this.bones.length);
  65062. for (var index = 0; index < this.bones.length; index++) {
  65063. this._sortBones(index, bones, visited);
  65064. }
  65065. this.bones = bones;
  65066. };
  65067. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65068. if (visited[index]) {
  65069. return;
  65070. }
  65071. visited[index] = true;
  65072. var bone = this.bones[index];
  65073. if (bone._index === undefined) {
  65074. bone._index = index;
  65075. }
  65076. var parentBone = bone.getParent();
  65077. if (parentBone) {
  65078. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65079. }
  65080. bones.push(bone);
  65081. };
  65082. return Skeleton;
  65083. }());
  65084. BABYLON.Skeleton = Skeleton;
  65085. })(BABYLON || (BABYLON = {}));
  65086. //# sourceMappingURL=babylon.skeleton.js.map
  65087. var BABYLON;
  65088. (function (BABYLON) {
  65089. var SphericalPolynomial = /** @class */ (function () {
  65090. function SphericalPolynomial() {
  65091. this.x = BABYLON.Vector3.Zero();
  65092. this.y = BABYLON.Vector3.Zero();
  65093. this.z = BABYLON.Vector3.Zero();
  65094. this.xx = BABYLON.Vector3.Zero();
  65095. this.yy = BABYLON.Vector3.Zero();
  65096. this.zz = BABYLON.Vector3.Zero();
  65097. this.xy = BABYLON.Vector3.Zero();
  65098. this.yz = BABYLON.Vector3.Zero();
  65099. this.zx = BABYLON.Vector3.Zero();
  65100. }
  65101. SphericalPolynomial.prototype.addAmbient = function (color) {
  65102. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65103. this.xx = this.xx.add(colorVector);
  65104. this.yy = this.yy.add(colorVector);
  65105. this.zz = this.zz.add(colorVector);
  65106. };
  65107. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65108. var result = new SphericalPolynomial();
  65109. result.x = harmonics.L11.scale(1.02333);
  65110. result.y = harmonics.L1_1.scale(1.02333);
  65111. result.z = harmonics.L10.scale(1.02333);
  65112. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65113. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65114. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65115. result.yz = harmonics.L2_1.scale(0.858086);
  65116. result.zx = harmonics.L21.scale(0.858086);
  65117. result.xy = harmonics.L2_2.scale(0.858086);
  65118. result.scale(1.0 / Math.PI);
  65119. return result;
  65120. };
  65121. SphericalPolynomial.prototype.scale = function (scale) {
  65122. this.x = this.x.scale(scale);
  65123. this.y = this.y.scale(scale);
  65124. this.z = this.z.scale(scale);
  65125. this.xx = this.xx.scale(scale);
  65126. this.yy = this.yy.scale(scale);
  65127. this.zz = this.zz.scale(scale);
  65128. this.yz = this.yz.scale(scale);
  65129. this.zx = this.zx.scale(scale);
  65130. this.xy = this.xy.scale(scale);
  65131. };
  65132. return SphericalPolynomial;
  65133. }());
  65134. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65135. var SphericalHarmonics = /** @class */ (function () {
  65136. function SphericalHarmonics() {
  65137. this.L00 = BABYLON.Vector3.Zero();
  65138. this.L1_1 = BABYLON.Vector3.Zero();
  65139. this.L10 = BABYLON.Vector3.Zero();
  65140. this.L11 = BABYLON.Vector3.Zero();
  65141. this.L2_2 = BABYLON.Vector3.Zero();
  65142. this.L2_1 = BABYLON.Vector3.Zero();
  65143. this.L20 = BABYLON.Vector3.Zero();
  65144. this.L21 = BABYLON.Vector3.Zero();
  65145. this.L22 = BABYLON.Vector3.Zero();
  65146. }
  65147. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65148. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65149. var c = colorVector.scale(deltaSolidAngle);
  65150. this.L00 = this.L00.add(c.scale(0.282095));
  65151. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65152. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65153. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65154. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65155. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65156. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65157. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65158. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65159. };
  65160. SphericalHarmonics.prototype.scale = function (scale) {
  65161. this.L00 = this.L00.scale(scale);
  65162. this.L1_1 = this.L1_1.scale(scale);
  65163. this.L10 = this.L10.scale(scale);
  65164. this.L11 = this.L11.scale(scale);
  65165. this.L2_2 = this.L2_2.scale(scale);
  65166. this.L2_1 = this.L2_1.scale(scale);
  65167. this.L20 = this.L20.scale(scale);
  65168. this.L21 = this.L21.scale(scale);
  65169. this.L22 = this.L22.scale(scale);
  65170. };
  65171. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65172. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65173. //
  65174. // E_lm = A_l * L_lm
  65175. //
  65176. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65177. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65178. // the scaling factors are given in equation 9.
  65179. // Constant (Band 0)
  65180. this.L00 = this.L00.scale(3.141593);
  65181. // Linear (Band 1)
  65182. this.L1_1 = this.L1_1.scale(2.094395);
  65183. this.L10 = this.L10.scale(2.094395);
  65184. this.L11 = this.L11.scale(2.094395);
  65185. // Quadratic (Band 2)
  65186. this.L2_2 = this.L2_2.scale(0.785398);
  65187. this.L2_1 = this.L2_1.scale(0.785398);
  65188. this.L20 = this.L20.scale(0.785398);
  65189. this.L21 = this.L21.scale(0.785398);
  65190. this.L22 = this.L22.scale(0.785398);
  65191. };
  65192. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65193. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65194. // L = (1/pi) * E * rho
  65195. //
  65196. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65197. this.scale(1.0 / Math.PI);
  65198. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65199. // (The pixel shader must apply albedo after texture fetches, etc).
  65200. };
  65201. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65202. var result = new SphericalHarmonics();
  65203. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65204. result.L1_1 = polynomial.y.scale(0.977204);
  65205. result.L10 = polynomial.z.scale(0.977204);
  65206. result.L11 = polynomial.x.scale(0.977204);
  65207. result.L2_2 = polynomial.xy.scale(1.16538);
  65208. result.L2_1 = polynomial.yz.scale(1.16538);
  65209. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65210. result.L21 = polynomial.zx.scale(1.16538);
  65211. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65212. result.scale(Math.PI);
  65213. return result;
  65214. };
  65215. return SphericalHarmonics;
  65216. }());
  65217. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65218. })(BABYLON || (BABYLON = {}));
  65219. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65220. var BABYLON;
  65221. (function (BABYLON) {
  65222. var FileFaceOrientation = /** @class */ (function () {
  65223. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65224. this.name = name;
  65225. this.worldAxisForNormal = worldAxisForNormal;
  65226. this.worldAxisForFileX = worldAxisForFileX;
  65227. this.worldAxisForFileY = worldAxisForFileY;
  65228. }
  65229. return FileFaceOrientation;
  65230. }());
  65231. ;
  65232. /**
  65233. * Helper class dealing with the extraction of spherical polynomial dataArray
  65234. * from a cube map.
  65235. */
  65236. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65237. function CubeMapToSphericalPolynomialTools() {
  65238. }
  65239. /**
  65240. * Converts a texture to the according Spherical Polynomial data.
  65241. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65242. *
  65243. * @param texture The texture to extract the information from.
  65244. * @return The Spherical Polynomial data.
  65245. */
  65246. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65247. if (!texture.isCube) {
  65248. // Only supports cube Textures currently.
  65249. return null;
  65250. }
  65251. var size = texture.getSize().width;
  65252. var right = texture.readPixels(0);
  65253. var left = texture.readPixels(1);
  65254. var up;
  65255. var down;
  65256. if (texture.isRenderTarget) {
  65257. up = texture.readPixels(3);
  65258. down = texture.readPixels(2);
  65259. }
  65260. else {
  65261. up = texture.readPixels(2);
  65262. down = texture.readPixels(3);
  65263. }
  65264. var front = texture.readPixels(4);
  65265. var back = texture.readPixels(5);
  65266. var gammaSpace = texture.gammaSpace;
  65267. // Always read as RGBA.
  65268. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65269. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65270. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65271. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65272. }
  65273. var cubeInfo = {
  65274. size: size,
  65275. right: right,
  65276. left: left,
  65277. up: up,
  65278. down: down,
  65279. front: front,
  65280. back: back,
  65281. format: format,
  65282. type: type,
  65283. gammaSpace: gammaSpace,
  65284. };
  65285. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65286. };
  65287. /**
  65288. * Converts a cubemap to the according Spherical Polynomial data.
  65289. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65290. *
  65291. * @param cubeInfo The Cube map to extract the information from.
  65292. * @return The Spherical Polynomial data.
  65293. */
  65294. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65295. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65296. var totalSolidAngle = 0.0;
  65297. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65298. var du = 2.0 / cubeInfo.size;
  65299. var dv = du;
  65300. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65301. var minUV = du * 0.5 - 1.0;
  65302. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65303. var fileFace = this.FileFaces[faceIndex];
  65304. var dataArray = cubeInfo[fileFace.name];
  65305. var v = minUV;
  65306. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65307. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65308. // Because SP is still linear, so summation is fine in that basis.
  65309. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65310. for (var y = 0; y < cubeInfo.size; y++) {
  65311. var u = minUV;
  65312. for (var x = 0; x < cubeInfo.size; x++) {
  65313. // World direction (not normalised)
  65314. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65315. worldDirection.normalize();
  65316. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65317. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65318. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65319. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65320. // Handle Integer types.
  65321. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65322. r /= 255;
  65323. g /= 255;
  65324. b /= 255;
  65325. }
  65326. // Handle Gamma space textures.
  65327. if (cubeInfo.gammaSpace) {
  65328. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65329. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65330. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65331. }
  65332. var color = new BABYLON.Color3(r, g, b);
  65333. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65334. totalSolidAngle += deltaSolidAngle;
  65335. u += du;
  65336. }
  65337. v += dv;
  65338. }
  65339. }
  65340. // Solid angle for entire sphere is 4*pi
  65341. var sphereSolidAngle = 4.0 * Math.PI;
  65342. // Adjust the solid angle to allow for how many faces we processed.
  65343. var facesProcessed = 6.0;
  65344. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65345. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65346. // This is needed because the numerical integration over the cube uses a
  65347. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65348. // and also to compensate for accumulative error due to float precision in the summation.
  65349. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65350. sphericalHarmonics.scale(correctionFactor);
  65351. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65352. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65353. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65354. };
  65355. CubeMapToSphericalPolynomialTools.FileFaces = [
  65356. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65357. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65358. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65359. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65360. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65361. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65362. ];
  65363. return CubeMapToSphericalPolynomialTools;
  65364. }());
  65365. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65366. })(BABYLON || (BABYLON = {}));
  65367. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65368. var BABYLON;
  65369. (function (BABYLON) {
  65370. /**
  65371. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65372. */
  65373. var PanoramaToCubeMapTools = /** @class */ (function () {
  65374. function PanoramaToCubeMapTools() {
  65375. }
  65376. /**
  65377. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65378. *
  65379. * @param float32Array The source data.
  65380. * @param inputWidth The width of the input panorama.
  65381. * @param inputhHeight The height of the input panorama.
  65382. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65383. * @return The cubemap data
  65384. */
  65385. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65386. if (!float32Array) {
  65387. throw "ConvertPanoramaToCubemap: input cannot be null";
  65388. }
  65389. if (float32Array.length != inputWidth * inputHeight * 3) {
  65390. throw "ConvertPanoramaToCubemap: input size is wrong";
  65391. }
  65392. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65393. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65394. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65395. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65396. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65397. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65398. return {
  65399. front: textureFront,
  65400. back: textureBack,
  65401. left: textureLeft,
  65402. right: textureRight,
  65403. up: textureUp,
  65404. down: textureDown,
  65405. size: size,
  65406. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65407. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65408. gammaSpace: false,
  65409. };
  65410. };
  65411. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65412. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65413. var textureArray = new Float32Array(buffer);
  65414. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65415. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65416. var dy = 1 / texSize;
  65417. var fy = 0;
  65418. for (var y = 0; y < texSize; y++) {
  65419. var xv1 = faceData[0];
  65420. var xv2 = faceData[2];
  65421. for (var x = 0; x < texSize; x++) {
  65422. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65423. v.normalize();
  65424. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65425. // 3 channels per pixels
  65426. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65427. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65428. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65429. xv1 = xv1.add(rotDX1);
  65430. xv2 = xv2.add(rotDX2);
  65431. }
  65432. fy += dy;
  65433. }
  65434. return textureArray;
  65435. };
  65436. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65437. var theta = Math.atan2(vDir.z, vDir.x);
  65438. var phi = Math.acos(vDir.y);
  65439. while (theta < -Math.PI)
  65440. theta += 2 * Math.PI;
  65441. while (theta > Math.PI)
  65442. theta -= 2 * Math.PI;
  65443. var dx = theta / Math.PI;
  65444. var dy = phi / Math.PI;
  65445. // recenter.
  65446. dx = dx * 0.5 + 0.5;
  65447. var px = Math.round(dx * inputWidth);
  65448. if (px < 0)
  65449. px = 0;
  65450. else if (px >= inputWidth)
  65451. px = inputWidth - 1;
  65452. var py = Math.round(dy * inputHeight);
  65453. if (py < 0)
  65454. py = 0;
  65455. else if (py >= inputHeight)
  65456. py = inputHeight - 1;
  65457. var inputY = (inputHeight - py - 1);
  65458. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65459. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65460. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65461. return {
  65462. r: r,
  65463. g: g,
  65464. b: b
  65465. };
  65466. };
  65467. PanoramaToCubeMapTools.FACE_FRONT = [
  65468. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65469. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65470. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65471. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65472. ];
  65473. PanoramaToCubeMapTools.FACE_BACK = [
  65474. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65475. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65476. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65477. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65478. ];
  65479. PanoramaToCubeMapTools.FACE_RIGHT = [
  65480. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65481. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65482. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65483. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65484. ];
  65485. PanoramaToCubeMapTools.FACE_LEFT = [
  65486. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65487. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65488. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65489. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65490. ];
  65491. PanoramaToCubeMapTools.FACE_DOWN = [
  65492. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65493. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65494. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65495. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65496. ];
  65497. PanoramaToCubeMapTools.FACE_UP = [
  65498. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65499. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65500. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65501. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65502. ];
  65503. return PanoramaToCubeMapTools;
  65504. }());
  65505. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65508. var BABYLON;
  65509. (function (BABYLON) {
  65510. ;
  65511. /**
  65512. * This groups tools to convert HDR texture to native colors array.
  65513. */
  65514. var HDRTools = /** @class */ (function () {
  65515. function HDRTools() {
  65516. }
  65517. HDRTools.Ldexp = function (mantissa, exponent) {
  65518. if (exponent > 1023) {
  65519. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65520. }
  65521. if (exponent < -1074) {
  65522. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65523. }
  65524. return mantissa * Math.pow(2, exponent);
  65525. };
  65526. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65527. if (exponent > 0) {
  65528. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65529. float32array[index + 0] = red * exponent;
  65530. float32array[index + 1] = green * exponent;
  65531. float32array[index + 2] = blue * exponent;
  65532. }
  65533. else {
  65534. float32array[index + 0] = 0;
  65535. float32array[index + 1] = 0;
  65536. float32array[index + 2] = 0;
  65537. }
  65538. };
  65539. HDRTools.readStringLine = function (uint8array, startIndex) {
  65540. var line = "";
  65541. var character = "";
  65542. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65543. character = String.fromCharCode(uint8array[i]);
  65544. if (character == "\n") {
  65545. break;
  65546. }
  65547. line += character;
  65548. }
  65549. return line;
  65550. };
  65551. /**
  65552. * Reads header information from an RGBE texture stored in a native array.
  65553. * More information on this format are available here:
  65554. * https://en.wikipedia.org/wiki/RGBE_image_format
  65555. *
  65556. * @param uint8array The binary file stored in native array.
  65557. * @return The header information.
  65558. */
  65559. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65560. var height = 0;
  65561. var width = 0;
  65562. var line = this.readStringLine(uint8array, 0);
  65563. if (line[0] != '#' || line[1] != '?') {
  65564. throw "Bad HDR Format.";
  65565. }
  65566. var endOfHeader = false;
  65567. var findFormat = false;
  65568. var lineIndex = 0;
  65569. do {
  65570. lineIndex += (line.length + 1);
  65571. line = this.readStringLine(uint8array, lineIndex);
  65572. if (line == "FORMAT=32-bit_rle_rgbe") {
  65573. findFormat = true;
  65574. }
  65575. else if (line.length == 0) {
  65576. endOfHeader = true;
  65577. }
  65578. } while (!endOfHeader);
  65579. if (!findFormat) {
  65580. throw "HDR Bad header format, unsupported FORMAT";
  65581. }
  65582. lineIndex += (line.length + 1);
  65583. line = this.readStringLine(uint8array, lineIndex);
  65584. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65585. var match = sizeRegexp.exec(line);
  65586. // TODO. Support +Y and -X if needed.
  65587. if (!match || match.length < 3) {
  65588. throw "HDR Bad header format, no size";
  65589. }
  65590. width = parseInt(match[2]);
  65591. height = parseInt(match[1]);
  65592. if (width < 8 || width > 0x7fff) {
  65593. throw "HDR Bad header format, unsupported size";
  65594. }
  65595. lineIndex += (line.length + 1);
  65596. return {
  65597. height: height,
  65598. width: width,
  65599. dataPosition: lineIndex
  65600. };
  65601. };
  65602. /**
  65603. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65604. * This RGBE texture needs to store the information as a panorama.
  65605. *
  65606. * More information on this format are available here:
  65607. * https://en.wikipedia.org/wiki/RGBE_image_format
  65608. *
  65609. * @param buffer The binary file stored in an array buffer.
  65610. * @param size The expected size of the extracted cubemap.
  65611. * @return The Cube Map information.
  65612. */
  65613. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65614. var uint8array = new Uint8Array(buffer);
  65615. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65616. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65617. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65618. return cubeMapData;
  65619. };
  65620. /**
  65621. * Returns the pixels data extracted from an RGBE texture.
  65622. * This pixels will be stored left to right up to down in the R G B order in one array.
  65623. *
  65624. * More information on this format are available here:
  65625. * https://en.wikipedia.org/wiki/RGBE_image_format
  65626. *
  65627. * @param uint8array The binary file stored in an array buffer.
  65628. * @param hdrInfo The header information of the file.
  65629. * @return The pixels data in RGB right to left up to down order.
  65630. */
  65631. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65632. // Keep for multi format supports.
  65633. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65634. };
  65635. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65636. var num_scanlines = hdrInfo.height;
  65637. var scanline_width = hdrInfo.width;
  65638. var a, b, c, d, count;
  65639. var dataIndex = hdrInfo.dataPosition;
  65640. var index = 0, endIndex = 0, i = 0;
  65641. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65642. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65643. // 3 channels of 4 bytes per pixel in float.
  65644. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65645. var resultArray = new Float32Array(resultBuffer);
  65646. // read in each successive scanline
  65647. while (num_scanlines > 0) {
  65648. a = uint8array[dataIndex++];
  65649. b = uint8array[dataIndex++];
  65650. c = uint8array[dataIndex++];
  65651. d = uint8array[dataIndex++];
  65652. if (a != 2 || b != 2 || (c & 0x80)) {
  65653. // this file is not run length encoded
  65654. throw "HDR Bad header format, not RLE";
  65655. }
  65656. if (((c << 8) | d) != scanline_width) {
  65657. throw "HDR Bad header format, wrong scan line width";
  65658. }
  65659. index = 0;
  65660. // read each of the four channels for the scanline into the buffer
  65661. for (i = 0; i < 4; i++) {
  65662. endIndex = (i + 1) * scanline_width;
  65663. while (index < endIndex) {
  65664. a = uint8array[dataIndex++];
  65665. b = uint8array[dataIndex++];
  65666. if (a > 128) {
  65667. // a run of the same value
  65668. count = a - 128;
  65669. if ((count == 0) || (count > endIndex - index)) {
  65670. throw "HDR Bad Format, bad scanline data (run)";
  65671. }
  65672. while (count-- > 0) {
  65673. scanLineArray[index++] = b;
  65674. }
  65675. }
  65676. else {
  65677. // a non-run
  65678. count = a;
  65679. if ((count == 0) || (count > endIndex - index)) {
  65680. throw "HDR Bad Format, bad scanline data (non-run)";
  65681. }
  65682. scanLineArray[index++] = b;
  65683. if (--count > 0) {
  65684. for (var j = 0; j < count; j++) {
  65685. scanLineArray[index++] = uint8array[dataIndex++];
  65686. }
  65687. }
  65688. }
  65689. }
  65690. }
  65691. // now convert data from buffer into floats
  65692. for (i = 0; i < scanline_width; i++) {
  65693. a = scanLineArray[i];
  65694. b = scanLineArray[i + scanline_width];
  65695. c = scanLineArray[i + 2 * scanline_width];
  65696. d = scanLineArray[i + 3 * scanline_width];
  65697. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65698. }
  65699. num_scanlines--;
  65700. }
  65701. return resultArray;
  65702. };
  65703. return HDRTools;
  65704. }());
  65705. BABYLON.HDRTools = HDRTools;
  65706. })(BABYLON || (BABYLON = {}));
  65707. //# sourceMappingURL=babylon.hdr.js.map
  65708. var BABYLON;
  65709. (function (BABYLON) {
  65710. /**
  65711. * This represents a texture coming from an HDR input.
  65712. *
  65713. * The only supported format is currently panorama picture stored in RGBE format.
  65714. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65715. */
  65716. var HDRCubeTexture = /** @class */ (function (_super) {
  65717. __extends(HDRCubeTexture, _super);
  65718. /**
  65719. * Instantiates an HDRTexture from the following parameters.
  65720. *
  65721. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65722. * @param scene The scene the texture will be used in
  65723. * @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.
  65724. * @param noMipmap Forces to not generate the mipmap if true
  65725. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  65726. * @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)
  65727. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65728. */
  65729. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65730. if (noMipmap === void 0) { noMipmap = false; }
  65731. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65732. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65733. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65734. if (onLoad === void 0) { onLoad = null; }
  65735. if (onError === void 0) { onError = null; }
  65736. var _this = _super.call(this, scene) || this;
  65737. _this._useInGammaSpace = false;
  65738. _this._generateHarmonics = true;
  65739. _this._isBABYLONPreprocessed = false;
  65740. _this._onLoad = null;
  65741. _this._onError = null;
  65742. /**
  65743. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65744. */
  65745. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65746. /**
  65747. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65748. * This is usefull at run time to apply the good shader.
  65749. */
  65750. _this.isPMREM = false;
  65751. _this._isBlocking = true;
  65752. if (!url) {
  65753. return _this;
  65754. }
  65755. _this.name = url;
  65756. _this.url = url;
  65757. _this.hasAlpha = false;
  65758. _this.isCube = true;
  65759. _this._textureMatrix = BABYLON.Matrix.Identity();
  65760. _this._onLoad = onLoad;
  65761. _this._onError = onError;
  65762. _this.gammaSpace = false;
  65763. var caps = scene.getEngine().getCaps();
  65764. if (size) {
  65765. _this._isBABYLONPreprocessed = false;
  65766. _this._noMipmap = noMipmap;
  65767. _this._size = size;
  65768. _this._useInGammaSpace = useInGammaSpace;
  65769. _this._usePMREMGenerator = usePMREMGenerator &&
  65770. caps.textureLOD &&
  65771. caps.textureFloat &&
  65772. !_this._useInGammaSpace;
  65773. }
  65774. else {
  65775. _this._isBABYLONPreprocessed = true;
  65776. _this._noMipmap = false;
  65777. _this._useInGammaSpace = false;
  65778. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65779. !_this._useInGammaSpace;
  65780. }
  65781. _this.isPMREM = _this._usePMREMGenerator;
  65782. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65783. if (!_this._texture) {
  65784. if (!scene.useDelayedTextureLoading) {
  65785. _this.loadTexture();
  65786. }
  65787. else {
  65788. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65789. }
  65790. }
  65791. return _this;
  65792. }
  65793. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65794. /**
  65795. * Gets wether or not the texture is blocking during loading.
  65796. */
  65797. get: function () {
  65798. return this._isBlocking;
  65799. },
  65800. /**
  65801. * Sets wether or not the texture is blocking during loading.
  65802. */
  65803. set: function (value) {
  65804. this._isBlocking = value;
  65805. },
  65806. enumerable: true,
  65807. configurable: true
  65808. });
  65809. /**
  65810. * Occurs when the file is a preprocessed .babylon.hdr file.
  65811. */
  65812. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65813. var _this = this;
  65814. var mipLevels = 0;
  65815. var floatArrayView = null;
  65816. var scene = this.getScene();
  65817. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65818. var mips = new Array();
  65819. if (!floatArrayView) {
  65820. return mips;
  65821. }
  65822. var startIndex = 30;
  65823. for (var level = 0; level < mipLevels; level++) {
  65824. mips.push([]);
  65825. // Fill each pixel of the mip level.
  65826. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65827. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65828. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65829. mips[level].push(faceData);
  65830. startIndex += faceSize;
  65831. }
  65832. }
  65833. return mips;
  65834. } : null;
  65835. var callback = function (buffer) {
  65836. var scene = _this.getScene();
  65837. if (!scene) {
  65838. return null;
  65839. }
  65840. // Create Native Array Views
  65841. var intArrayView = new Int32Array(buffer);
  65842. floatArrayView = new Float32Array(buffer);
  65843. // Fill header.
  65844. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65845. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65846. // Update Texture Information.
  65847. if (!_this._texture) {
  65848. return null;
  65849. }
  65850. _this._texture.updateSize(_this._size, _this._size);
  65851. // Fill polynomial information.
  65852. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65853. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65854. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65855. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65856. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65857. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65858. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65859. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65860. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65861. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65862. _this.sphericalPolynomial = sphericalPolynomial;
  65863. // Fill pixel data.
  65864. mipLevels = intArrayView[29]; // Number of mip levels.
  65865. var startIndex = 30;
  65866. var data = [];
  65867. var faceSize = Math.pow(_this._size, 2) * 3;
  65868. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65869. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65870. startIndex += faceSize;
  65871. }
  65872. var results = [];
  65873. var byteArray = null;
  65874. // Push each faces.
  65875. for (var k = 0; k < 6; k++) {
  65876. var dataFace = null;
  65877. // To be deprecated.
  65878. if (version === 1) {
  65879. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65880. dataFace = data[j];
  65881. }
  65882. // If special cases.
  65883. if (!mipmapGenerator && dataFace) {
  65884. if (!scene.getEngine().getCaps().textureFloat) {
  65885. // 3 channels of 1 bytes per pixel in bytes.
  65886. var byteBuffer = new ArrayBuffer(faceSize);
  65887. byteArray = new Uint8Array(byteBuffer);
  65888. }
  65889. for (var i = 0; i < _this._size * _this._size; i++) {
  65890. // Put in gamma space if requested.
  65891. if (_this._useInGammaSpace) {
  65892. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65893. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65894. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65895. }
  65896. // Convert to int texture for fallback.
  65897. if (byteArray) {
  65898. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65899. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65900. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65901. // May use luminance instead if the result is not accurate.
  65902. var max = Math.max(Math.max(r, g), b);
  65903. if (max > 255) {
  65904. var scale = 255 / max;
  65905. r *= scale;
  65906. g *= scale;
  65907. b *= scale;
  65908. }
  65909. byteArray[(i * 3) + 0] = r;
  65910. byteArray[(i * 3) + 1] = g;
  65911. byteArray[(i * 3) + 2] = b;
  65912. }
  65913. }
  65914. }
  65915. // Fill the array accordingly.
  65916. if (byteArray) {
  65917. results.push(byteArray);
  65918. }
  65919. else {
  65920. results.push(dataFace);
  65921. }
  65922. }
  65923. return results;
  65924. };
  65925. if (scene) {
  65926. 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);
  65927. }
  65928. };
  65929. /**
  65930. * Occurs when the file is raw .hdr file.
  65931. */
  65932. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65933. var _this = this;
  65934. var callback = function (buffer) {
  65935. var scene = _this.getScene();
  65936. if (!scene) {
  65937. return null;
  65938. }
  65939. // Extract the raw linear data.
  65940. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65941. // Generate harmonics if needed.
  65942. if (_this._generateHarmonics) {
  65943. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65944. _this.sphericalPolynomial = sphericalPolynomial;
  65945. }
  65946. var results = [];
  65947. var byteArray = null;
  65948. // Push each faces.
  65949. for (var j = 0; j < 6; j++) {
  65950. // Create uintarray fallback.
  65951. if (!scene.getEngine().getCaps().textureFloat) {
  65952. // 3 channels of 1 bytes per pixel in bytes.
  65953. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65954. byteArray = new Uint8Array(byteBuffer);
  65955. }
  65956. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65957. // If special cases.
  65958. if (_this._useInGammaSpace || byteArray) {
  65959. for (var i = 0; i < _this._size * _this._size; i++) {
  65960. // Put in gamma space if requested.
  65961. if (_this._useInGammaSpace) {
  65962. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65963. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65964. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65965. }
  65966. // Convert to int texture for fallback.
  65967. if (byteArray) {
  65968. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65969. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65970. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65971. // May use luminance instead if the result is not accurate.
  65972. var max = Math.max(Math.max(r, g), b);
  65973. if (max > 255) {
  65974. var scale = 255 / max;
  65975. r *= scale;
  65976. g *= scale;
  65977. b *= scale;
  65978. }
  65979. byteArray[(i * 3) + 0] = r;
  65980. byteArray[(i * 3) + 1] = g;
  65981. byteArray[(i * 3) + 2] = b;
  65982. }
  65983. }
  65984. }
  65985. if (byteArray) {
  65986. results.push(byteArray);
  65987. }
  65988. else {
  65989. results.push(dataFace);
  65990. }
  65991. }
  65992. return results;
  65993. };
  65994. var mipmapGenerator = null;
  65995. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  65996. // if (!this._noMipmap &&
  65997. // this._usePMREMGenerator) {
  65998. // mipmapGenerator = (data: ArrayBufferView[]) => {
  65999. // // Custom setup of the generator matching with the PBR shader values.
  66000. // var generator = new BABYLON.PMREMGenerator(data,
  66001. // this._size,
  66002. // this._size,
  66003. // 0,
  66004. // 3,
  66005. // this.getScene().getEngine().getCaps().textureFloat,
  66006. // 2048,
  66007. // 0.25,
  66008. // false,
  66009. // true);
  66010. // return generator.filterCubeMap();
  66011. // };
  66012. // }
  66013. var scene = this.getScene();
  66014. if (scene) {
  66015. 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);
  66016. }
  66017. };
  66018. /**
  66019. * Starts the loading process of the texture.
  66020. */
  66021. HDRCubeTexture.prototype.loadTexture = function () {
  66022. if (this._isBABYLONPreprocessed) {
  66023. this.loadBabylonTexture();
  66024. }
  66025. else {
  66026. this.loadHDRTexture();
  66027. }
  66028. };
  66029. HDRCubeTexture.prototype.clone = function () {
  66030. var scene = this.getScene();
  66031. if (!scene) {
  66032. return this;
  66033. }
  66034. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66035. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66036. // Base texture
  66037. newTexture.level = this.level;
  66038. newTexture.wrapU = this.wrapU;
  66039. newTexture.wrapV = this.wrapV;
  66040. newTexture.coordinatesIndex = this.coordinatesIndex;
  66041. newTexture.coordinatesMode = this.coordinatesMode;
  66042. return newTexture;
  66043. };
  66044. // Methods
  66045. HDRCubeTexture.prototype.delayLoad = function () {
  66046. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66047. return;
  66048. }
  66049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66050. this._texture = this._getFromCache(this.url, this._noMipmap);
  66051. if (!this._texture) {
  66052. this.loadTexture();
  66053. }
  66054. };
  66055. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66056. return this._textureMatrix;
  66057. };
  66058. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66059. this._textureMatrix = value;
  66060. };
  66061. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66062. var texture = null;
  66063. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66064. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66065. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66066. texture.name = parsedTexture.name;
  66067. texture.hasAlpha = parsedTexture.hasAlpha;
  66068. texture.level = parsedTexture.level;
  66069. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66070. texture.isBlocking = parsedTexture.isBlocking;
  66071. }
  66072. return texture;
  66073. };
  66074. HDRCubeTexture.prototype.serialize = function () {
  66075. if (!this.name) {
  66076. return null;
  66077. }
  66078. var serializationObject = {};
  66079. serializationObject.name = this.name;
  66080. serializationObject.hasAlpha = this.hasAlpha;
  66081. serializationObject.isCube = true;
  66082. serializationObject.level = this.level;
  66083. serializationObject.size = this._size;
  66084. serializationObject.coordinatesMode = this.coordinatesMode;
  66085. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66086. serializationObject.generateHarmonics = this._generateHarmonics;
  66087. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66088. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66089. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66090. serializationObject.noMipmap = this._noMipmap;
  66091. serializationObject.isBlocking = this._isBlocking;
  66092. return serializationObject;
  66093. };
  66094. /**
  66095. * Saves as a file the data contained in the texture in a binary format.
  66096. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66097. * as the spherical used in the lighting.
  66098. * @param url The HDR file url.
  66099. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66100. * @param onError Method called if any error happens during download.
  66101. * @return The packed binary data.
  66102. */
  66103. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66104. if (onError === void 0) { onError = null; }
  66105. var callback = function (buffer) {
  66106. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66107. // Returns a URL you can use as a href.
  66108. var objUrl = window.URL.createObjectURL(data);
  66109. // Simulates a link to it and click to dowload.
  66110. var a = document.createElement("a");
  66111. document.body.appendChild(a);
  66112. a.style.display = "none";
  66113. a.href = objUrl;
  66114. a.download = "envmap.babylon.hdr";
  66115. a.click();
  66116. };
  66117. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66118. };
  66119. /**
  66120. * Serializes the data contained in the texture in a binary format.
  66121. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66122. * as the spherical used in the lighting.
  66123. * @param url The HDR file url.
  66124. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66125. * @param onError Method called if any error happens during download.
  66126. * @return The packed binary data.
  66127. */
  66128. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66129. if (onError === void 0) { onError = null; }
  66130. // Needs the url tho create the texture.
  66131. if (!url) {
  66132. return;
  66133. }
  66134. // Check Power of two size.
  66135. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66136. return;
  66137. }
  66138. // Coming Back in 3.x.
  66139. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66140. };
  66141. HDRCubeTexture._facesMapping = [
  66142. "right",
  66143. "left",
  66144. "up",
  66145. "down",
  66146. "front",
  66147. "back"
  66148. ];
  66149. return HDRCubeTexture;
  66150. }(BABYLON.BaseTexture));
  66151. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66152. })(BABYLON || (BABYLON = {}));
  66153. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66154. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66155. // Huge respect for a such great lib.
  66156. // Earcut license:
  66157. // Copyright (c) 2016, Mapbox
  66158. //
  66159. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66160. // with or without fee is hereby granted, provided that the above copyright notice
  66161. // and this permission notice appear in all copies.
  66162. //
  66163. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66164. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66165. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66166. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66167. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66168. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66169. // THIS SOFTWARE.
  66170. var Earcut;
  66171. (function (Earcut) {
  66172. /**
  66173. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66174. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66175. * @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).
  66176. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66177. */
  66178. function earcut(data, holeIndices, dim) {
  66179. dim = dim || 2;
  66180. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66181. if (!outerNode)
  66182. return triangles;
  66183. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66184. if (hasHoles)
  66185. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66186. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66187. if (data.length > 80 * dim) {
  66188. minX = maxX = data[0];
  66189. minY = maxY = data[1];
  66190. for (var i = dim; i < outerLen; i += dim) {
  66191. x = data[i];
  66192. y = data[i + 1];
  66193. if (x < minX)
  66194. minX = x;
  66195. if (y < minY)
  66196. minY = y;
  66197. if (x > maxX)
  66198. maxX = x;
  66199. if (y > maxY)
  66200. maxY = y;
  66201. }
  66202. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66203. size = Math.max(maxX - minX, maxY - minY);
  66204. }
  66205. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66206. return triangles;
  66207. }
  66208. Earcut.earcut = earcut;
  66209. var Node = /** @class */ (function () {
  66210. function Node(i, x, y) {
  66211. this.i = i;
  66212. this.x = x;
  66213. this.y = y;
  66214. this.prev = null;
  66215. this.next = null;
  66216. this.z = null;
  66217. this.prevZ = null;
  66218. this.nextZ = null;
  66219. this.steiner = false;
  66220. }
  66221. return Node;
  66222. }());
  66223. // create a circular doubly linked list from polygon points in the specified winding order
  66224. function linkedList(data, start, end, dim, clockwise) {
  66225. var i, last = null;
  66226. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66227. for (i = start; i < end; i += dim)
  66228. last = insertNode(i, data[i], data[i + 1], last);
  66229. }
  66230. else {
  66231. for (i = end - dim; i >= start; i -= dim)
  66232. last = insertNode(i, data[i], data[i + 1], last);
  66233. }
  66234. if (last && equals(last, last.next)) {
  66235. removeNode(last);
  66236. last = last.next;
  66237. }
  66238. return last;
  66239. }
  66240. // eliminate colinear or duplicate points
  66241. function filterPoints(start, end) {
  66242. if (!start)
  66243. return start;
  66244. if (!end)
  66245. end = start;
  66246. var p = start, again;
  66247. do {
  66248. again = false;
  66249. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66250. removeNode(p);
  66251. p = end = p.prev;
  66252. if (p === p.next)
  66253. return undefined;
  66254. again = true;
  66255. }
  66256. else {
  66257. p = p.next;
  66258. }
  66259. } while (again || p !== end);
  66260. return end;
  66261. }
  66262. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66263. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66264. if (!ear)
  66265. return;
  66266. // interlink polygon nodes in z-order
  66267. if (!pass && size)
  66268. indexCurve(ear, minX, minY, size);
  66269. var stop = ear, prev, next;
  66270. // iterate through ears, slicing them one by one
  66271. while (ear.prev !== ear.next) {
  66272. prev = ear.prev;
  66273. next = ear.next;
  66274. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66275. // cut off the triangle
  66276. triangles.push(prev.i / dim);
  66277. triangles.push(ear.i / dim);
  66278. triangles.push(next.i / dim);
  66279. removeNode(ear);
  66280. // skipping the next vertice leads to less sliver triangles
  66281. ear = next.next;
  66282. stop = next.next;
  66283. continue;
  66284. }
  66285. ear = next;
  66286. // if we looped through the whole remaining polygon and can't find any more ears
  66287. if (ear === stop) {
  66288. // try filtering points and slicing again
  66289. if (!pass) {
  66290. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66291. // if this didn't work, try curing all small self-intersections locally
  66292. }
  66293. else if (pass === 1) {
  66294. ear = cureLocalIntersections(ear, triangles, dim);
  66295. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66296. // as a last resort, try splitting the remaining polygon into two
  66297. }
  66298. else if (pass === 2) {
  66299. splitEarcut(ear, triangles, dim, minX, minY, size);
  66300. }
  66301. break;
  66302. }
  66303. }
  66304. }
  66305. // check whether a polygon node forms a valid ear with adjacent nodes
  66306. function isEar(ear) {
  66307. var a = ear.prev, b = ear, c = ear.next;
  66308. if (area(a, b, c) >= 0)
  66309. return false; // reflex, can't be an ear
  66310. // now make sure we don't have other points inside the potential ear
  66311. var p = ear.next.next;
  66312. while (p !== ear.prev) {
  66313. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66314. area(p.prev, p, p.next) >= 0)
  66315. return false;
  66316. p = p.next;
  66317. }
  66318. return true;
  66319. }
  66320. function isEarHashed(ear, minX, minY, size) {
  66321. var a = ear.prev, b = ear, c = ear.next;
  66322. if (area(a, b, c) >= 0)
  66323. return false; // reflex, can't be an ear
  66324. // triangle bbox; min & max are calculated like this for speed
  66325. 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);
  66326. // z-order range for the current triangle bbox;
  66327. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66328. // first look for points inside the triangle in increasing z-order
  66329. var p = ear.nextZ;
  66330. while (p && p.z <= maxZ) {
  66331. if (p !== ear.prev &&
  66332. p !== ear.next &&
  66333. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66334. area(p.prev, p, p.next) >= 0)
  66335. return false;
  66336. p = p.nextZ;
  66337. }
  66338. // then look for points in decreasing z-order
  66339. p = ear.prevZ;
  66340. while (p && p.z >= minZ) {
  66341. if (p !== ear.prev &&
  66342. p !== ear.next &&
  66343. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66344. area(p.prev, p, p.next) >= 0)
  66345. return false;
  66346. p = p.prevZ;
  66347. }
  66348. return true;
  66349. }
  66350. // go through all polygon nodes and cure small local self-intersections
  66351. function cureLocalIntersections(start, triangles, dim) {
  66352. var p = start;
  66353. do {
  66354. var a = p.prev, b = p.next.next;
  66355. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66356. triangles.push(a.i / dim);
  66357. triangles.push(p.i / dim);
  66358. triangles.push(b.i / dim);
  66359. // remove two nodes involved
  66360. removeNode(p);
  66361. removeNode(p.next);
  66362. p = start = b;
  66363. }
  66364. p = p.next;
  66365. } while (p !== start);
  66366. return p;
  66367. }
  66368. // try splitting polygon into two and triangulate them independently
  66369. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66370. // look for a valid diagonal that divides the polygon into two
  66371. var a = start;
  66372. do {
  66373. var b = a.next.next;
  66374. while (b !== a.prev) {
  66375. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66376. // split the polygon in two by the diagonal
  66377. var c = splitPolygon(a, b);
  66378. // filter colinear points around the cuts
  66379. a = filterPoints(a, a.next);
  66380. c = filterPoints(c, c.next);
  66381. // run earcut on each half
  66382. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66383. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66384. return;
  66385. }
  66386. b = b.next;
  66387. }
  66388. a = a.next;
  66389. } while (a !== start);
  66390. }
  66391. // link every hole into the outer loop, producing a single-ring polygon without holes
  66392. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66393. var queue = [], i, len, start, end, list;
  66394. for (i = 0, len = holeIndices.length; i < len; i++) {
  66395. start = holeIndices[i] * dim;
  66396. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66397. list = linkedList(data, start, end, dim, false);
  66398. if (list === list.next)
  66399. list.steiner = true;
  66400. queue.push(getLeftmost(list));
  66401. }
  66402. queue.sort(compareX);
  66403. // process holes from left to right
  66404. for (i = 0; i < queue.length; i++) {
  66405. eliminateHole(queue[i], outerNode);
  66406. outerNode = filterPoints(outerNode, outerNode.next);
  66407. }
  66408. return outerNode;
  66409. }
  66410. function compareX(a, b) {
  66411. return a.x - b.x;
  66412. }
  66413. // find a bridge between vertices that connects hole with an outer ring and and link it
  66414. function eliminateHole(hole, outerNode) {
  66415. outerNode = findHoleBridge(hole, outerNode);
  66416. if (outerNode) {
  66417. var b = splitPolygon(outerNode, hole);
  66418. filterPoints(b, b.next);
  66419. }
  66420. }
  66421. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66422. function findHoleBridge(hole, outerNode) {
  66423. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66424. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66425. // segment's endpoint with lesser x will be potential connection point
  66426. do {
  66427. if (hy <= p.y && hy >= p.next.y) {
  66428. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66429. if (x <= hx && x > qx) {
  66430. qx = x;
  66431. if (x === hx) {
  66432. if (hy === p.y)
  66433. return p;
  66434. if (hy === p.next.y)
  66435. return p.next;
  66436. }
  66437. m = p.x < p.next.x ? p : p.next;
  66438. }
  66439. }
  66440. p = p.next;
  66441. } while (p !== outerNode);
  66442. if (!m)
  66443. return null;
  66444. if (hx === qx)
  66445. return m.prev; // hole touches outer segment; pick lower endpoint
  66446. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66447. // if there are no points found, we have a valid connection;
  66448. // otherwise choose the point of the minimum angle with the ray as connection point
  66449. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66450. p = m.next;
  66451. while (p !== stop) {
  66452. if (hx >= p.x &&
  66453. p.x >= mx &&
  66454. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66455. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66456. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66457. m = p;
  66458. tanMin = tan;
  66459. }
  66460. }
  66461. p = p.next;
  66462. }
  66463. return m;
  66464. }
  66465. // interlink polygon nodes in z-order
  66466. function indexCurve(start, minX, minY, size) {
  66467. var p = start;
  66468. do {
  66469. if (p.z === null)
  66470. p.z = zOrder(p.x, p.y, minX, minY, size);
  66471. p.prevZ = p.prev;
  66472. p.nextZ = p.next;
  66473. p = p.next;
  66474. } while (p !== start);
  66475. p.prevZ.nextZ = null;
  66476. p.prevZ = null;
  66477. sortLinked(p);
  66478. }
  66479. // Simon Tatham's linked list merge sort algorithm
  66480. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66481. function sortLinked(list) {
  66482. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66483. do {
  66484. p = list;
  66485. list = null;
  66486. tail = null;
  66487. numMerges = 0;
  66488. while (p) {
  66489. numMerges++;
  66490. q = p;
  66491. pSize = 0;
  66492. for (i = 0; i < inSize; i++) {
  66493. pSize++;
  66494. q = q.nextZ;
  66495. if (!q)
  66496. break;
  66497. }
  66498. qSize = inSize;
  66499. while (pSize > 0 || (qSize > 0 && q)) {
  66500. if (pSize === 0) {
  66501. e = q;
  66502. q = q.nextZ;
  66503. qSize--;
  66504. }
  66505. else if (qSize === 0 || !q) {
  66506. e = p;
  66507. p = p.nextZ;
  66508. pSize--;
  66509. }
  66510. else if (p.z <= q.z) {
  66511. e = p;
  66512. p = p.nextZ;
  66513. pSize--;
  66514. }
  66515. else {
  66516. e = q;
  66517. q = q.nextZ;
  66518. qSize--;
  66519. }
  66520. if (tail)
  66521. tail.nextZ = e;
  66522. else
  66523. list = e;
  66524. e.prevZ = tail;
  66525. tail = e;
  66526. }
  66527. p = q;
  66528. }
  66529. tail.nextZ = null;
  66530. inSize *= 2;
  66531. } while (numMerges > 1);
  66532. return list;
  66533. }
  66534. // z-order of a point given coords and size of the data bounding box
  66535. function zOrder(x, y, minX, minY, size) {
  66536. // coords are transformed into non-negative 15-bit integer range
  66537. x = 32767 * (x - minX) / size;
  66538. y = 32767 * (y - minY) / size;
  66539. x = (x | (x << 8)) & 0x00FF00FF;
  66540. x = (x | (x << 4)) & 0x0F0F0F0F;
  66541. x = (x | (x << 2)) & 0x33333333;
  66542. x = (x | (x << 1)) & 0x55555555;
  66543. y = (y | (y << 8)) & 0x00FF00FF;
  66544. y = (y | (y << 4)) & 0x0F0F0F0F;
  66545. y = (y | (y << 2)) & 0x33333333;
  66546. y = (y | (y << 1)) & 0x55555555;
  66547. return x | (y << 1);
  66548. }
  66549. // find the leftmost node of a polygon ring
  66550. function getLeftmost(start) {
  66551. var p = start, leftmost = start;
  66552. do {
  66553. if (p.x < leftmost.x)
  66554. leftmost = p;
  66555. p = p.next;
  66556. } while (p !== start);
  66557. return leftmost;
  66558. }
  66559. // check if a point lies within a convex triangle
  66560. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66561. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66562. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66563. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66564. }
  66565. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66566. function isValidDiagonal(a, b) {
  66567. return a.next.i !== b.i &&
  66568. a.prev.i !== b.i &&
  66569. !intersectsPolygon(a, b) &&
  66570. locallyInside(a, b) &&
  66571. locallyInside(b, a) &&
  66572. middleInside(a, b);
  66573. }
  66574. // signed area of a triangle
  66575. function area(p, q, r) {
  66576. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66577. }
  66578. // check if two points are equal
  66579. function equals(p1, p2) {
  66580. return p1.x === p2.x && p1.y === p2.y;
  66581. }
  66582. // check if two segments intersect
  66583. function intersects(p1, q1, p2, q2) {
  66584. if ((equals(p1, q1) && equals(p2, q2)) ||
  66585. (equals(p1, q2) && equals(p2, q1)))
  66586. return true;
  66587. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66588. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66589. }
  66590. // check if a polygon diagonal intersects any polygon segments
  66591. function intersectsPolygon(a, b) {
  66592. var p = a;
  66593. do {
  66594. if (p.i !== a.i &&
  66595. p.next.i !== a.i &&
  66596. p.i !== b.i &&
  66597. p.next.i !== b.i &&
  66598. intersects(p, p.next, a, b))
  66599. return true;
  66600. p = p.next;
  66601. } while (p !== a);
  66602. return false;
  66603. }
  66604. // check if a polygon diagonal is locally inside the polygon
  66605. function locallyInside(a, b) {
  66606. return area(a.prev, a, a.next) < 0
  66607. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66608. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66609. }
  66610. // check if the middle point of a polygon diagonal is inside the polygon
  66611. function middleInside(a, b) {
  66612. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66613. do {
  66614. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66615. inside = !inside;
  66616. p = p.next;
  66617. } while (p !== a);
  66618. return inside;
  66619. }
  66620. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66621. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66622. function splitPolygon(a, b) {
  66623. 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;
  66624. a.next = b;
  66625. b.prev = a;
  66626. a2.next = an;
  66627. an.prev = a2;
  66628. b2.next = a2;
  66629. a2.prev = b2;
  66630. bp.next = b2;
  66631. b2.prev = bp;
  66632. return b2;
  66633. }
  66634. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66635. function insertNode(i, x, y, last) {
  66636. var p = new Node(i, x, y);
  66637. if (!last) {
  66638. p.prev = p;
  66639. p.next = p;
  66640. }
  66641. else {
  66642. p.next = last.next;
  66643. p.prev = last;
  66644. last.next.prev = p;
  66645. last.next = p;
  66646. }
  66647. return p;
  66648. }
  66649. function removeNode(p) {
  66650. p.next.prev = p.prev;
  66651. p.prev.next = p.next;
  66652. if (p.prevZ)
  66653. p.prevZ.nextZ = p.nextZ;
  66654. if (p.nextZ)
  66655. p.nextZ.prevZ = p.prevZ;
  66656. }
  66657. /**
  66658. * return a percentage difference between the polygon area and its triangulation area;
  66659. * used to verify correctness of triangulation
  66660. */
  66661. function deviation(data, holeIndices, dim, triangles) {
  66662. var hasHoles = holeIndices && holeIndices.length;
  66663. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66664. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66665. if (hasHoles) {
  66666. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66667. var start = holeIndices[i] * dim;
  66668. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66669. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66670. }
  66671. }
  66672. var trianglesArea = 0;
  66673. for (i = 0; i < triangles.length; i += 3) {
  66674. var a = triangles[i] * dim;
  66675. var b = triangles[i + 1] * dim;
  66676. var c = triangles[i + 2] * dim;
  66677. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66678. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66679. }
  66680. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66681. }
  66682. Earcut.deviation = deviation;
  66683. ;
  66684. function signedArea(data, start, end, dim) {
  66685. var sum = 0;
  66686. for (var i = start, j = end - dim; i < end; i += dim) {
  66687. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66688. j = i;
  66689. }
  66690. return sum;
  66691. }
  66692. /**
  66693. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66694. */
  66695. function flatten(data) {
  66696. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66697. for (var i = 0; i < data.length; i++) {
  66698. for (var j = 0; j < data[i].length; j++) {
  66699. for (var d = 0; d < dim; d++)
  66700. result.vertices.push(data[i][j][d]);
  66701. }
  66702. if (i > 0) {
  66703. holeIndex += data[i - 1].length;
  66704. result.holes.push(holeIndex);
  66705. }
  66706. }
  66707. return result;
  66708. }
  66709. Earcut.flatten = flatten;
  66710. ;
  66711. })(Earcut || (Earcut = {}));
  66712. //# sourceMappingURL=babylon.earcut.js.map
  66713. var BABYLON;
  66714. (function (BABYLON) {
  66715. var IndexedVector2 = /** @class */ (function (_super) {
  66716. __extends(IndexedVector2, _super);
  66717. function IndexedVector2(original, index) {
  66718. var _this = _super.call(this, original.x, original.y) || this;
  66719. _this.index = index;
  66720. return _this;
  66721. }
  66722. return IndexedVector2;
  66723. }(BABYLON.Vector2));
  66724. var PolygonPoints = /** @class */ (function () {
  66725. function PolygonPoints() {
  66726. this.elements = new Array();
  66727. }
  66728. PolygonPoints.prototype.add = function (originalPoints) {
  66729. var _this = this;
  66730. var result = new Array();
  66731. originalPoints.forEach(function (point) {
  66732. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66733. var newPoint = new IndexedVector2(point, _this.elements.length);
  66734. result.push(newPoint);
  66735. _this.elements.push(newPoint);
  66736. }
  66737. });
  66738. return result;
  66739. };
  66740. PolygonPoints.prototype.computeBounds = function () {
  66741. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66742. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66743. this.elements.forEach(function (point) {
  66744. // x
  66745. if (point.x < lmin.x) {
  66746. lmin.x = point.x;
  66747. }
  66748. else if (point.x > lmax.x) {
  66749. lmax.x = point.x;
  66750. }
  66751. // y
  66752. if (point.y < lmin.y) {
  66753. lmin.y = point.y;
  66754. }
  66755. else if (point.y > lmax.y) {
  66756. lmax.y = point.y;
  66757. }
  66758. });
  66759. return {
  66760. min: lmin,
  66761. max: lmax,
  66762. width: lmax.x - lmin.x,
  66763. height: lmax.y - lmin.y
  66764. };
  66765. };
  66766. return PolygonPoints;
  66767. }());
  66768. var Polygon = /** @class */ (function () {
  66769. function Polygon() {
  66770. }
  66771. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66772. return [
  66773. new BABYLON.Vector2(xmin, ymin),
  66774. new BABYLON.Vector2(xmax, ymin),
  66775. new BABYLON.Vector2(xmax, ymax),
  66776. new BABYLON.Vector2(xmin, ymax)
  66777. ];
  66778. };
  66779. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66780. if (cx === void 0) { cx = 0; }
  66781. if (cy === void 0) { cy = 0; }
  66782. if (numberOfSides === void 0) { numberOfSides = 32; }
  66783. var result = new Array();
  66784. var angle = 0;
  66785. var increment = (Math.PI * 2) / numberOfSides;
  66786. for (var i = 0; i < numberOfSides; i++) {
  66787. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66788. angle -= increment;
  66789. }
  66790. return result;
  66791. };
  66792. Polygon.Parse = function (input) {
  66793. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66794. var i, result = [];
  66795. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66796. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66797. }
  66798. return result;
  66799. };
  66800. Polygon.StartingAt = function (x, y) {
  66801. return BABYLON.Path2.StartingAt(x, y);
  66802. };
  66803. return Polygon;
  66804. }());
  66805. BABYLON.Polygon = Polygon;
  66806. var PolygonMeshBuilder = /** @class */ (function () {
  66807. function PolygonMeshBuilder(name, contours, scene) {
  66808. this._points = new PolygonPoints();
  66809. this._outlinepoints = new PolygonPoints();
  66810. this._holes = new Array();
  66811. this._epoints = new Array();
  66812. this._eholes = new Array();
  66813. this._name = name;
  66814. this._scene = scene;
  66815. var points;
  66816. if (contours instanceof BABYLON.Path2) {
  66817. points = contours.getPoints();
  66818. }
  66819. else {
  66820. points = contours;
  66821. }
  66822. this._addToepoint(points);
  66823. this._points.add(points);
  66824. this._outlinepoints.add(points);
  66825. }
  66826. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66827. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66828. var p = points_1[_i];
  66829. this._epoints.push(p.x, p.y);
  66830. }
  66831. };
  66832. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66833. this._points.add(hole);
  66834. var holepoints = new PolygonPoints();
  66835. holepoints.add(hole);
  66836. this._holes.push(holepoints);
  66837. this._eholes.push(this._epoints.length / 2);
  66838. this._addToepoint(hole);
  66839. return this;
  66840. };
  66841. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66842. var _this = this;
  66843. if (updatable === void 0) { updatable = false; }
  66844. if (depth === void 0) { depth = 0; }
  66845. var result = new BABYLON.Mesh(this._name, this._scene);
  66846. var normals = new Array();
  66847. var positions = new Array();
  66848. var uvs = new Array();
  66849. var bounds = this._points.computeBounds();
  66850. this._points.elements.forEach(function (p) {
  66851. normals.push(0, 1.0, 0);
  66852. positions.push(p.x, 0, p.y);
  66853. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66854. });
  66855. var indices = new Array();
  66856. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66857. for (var i = 0; i < res.length; i++) {
  66858. indices.push(res[i]);
  66859. }
  66860. if (depth > 0) {
  66861. var positionscount = (positions.length / 3); //get the current pointcount
  66862. this._points.elements.forEach(function (p) {
  66863. normals.push(0, -1.0, 0);
  66864. positions.push(p.x, -depth, p.y);
  66865. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66866. });
  66867. var totalCount = indices.length;
  66868. for (var i = 0; i < totalCount; i += 3) {
  66869. var i0 = indices[i + 0];
  66870. var i1 = indices[i + 1];
  66871. var i2 = indices[i + 2];
  66872. indices.push(i2 + positionscount);
  66873. indices.push(i1 + positionscount);
  66874. indices.push(i0 + positionscount);
  66875. }
  66876. //Add the sides
  66877. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66878. this._holes.forEach(function (hole) {
  66879. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66880. });
  66881. }
  66882. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66883. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66884. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66885. result.setIndices(indices);
  66886. return result;
  66887. };
  66888. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66889. var StartIndex = positions.length / 3;
  66890. var ulength = 0;
  66891. for (var i = 0; i < points.elements.length; i++) {
  66892. var p = points.elements[i];
  66893. var p1;
  66894. if ((i + 1) > points.elements.length - 1) {
  66895. p1 = points.elements[0];
  66896. }
  66897. else {
  66898. p1 = points.elements[i + 1];
  66899. }
  66900. positions.push(p.x, 0, p.y);
  66901. positions.push(p.x, -depth, p.y);
  66902. positions.push(p1.x, 0, p1.y);
  66903. positions.push(p1.x, -depth, p1.y);
  66904. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66905. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66906. var v3 = v2.subtract(v1);
  66907. var v4 = new BABYLON.Vector3(0, 1, 0);
  66908. var vn = BABYLON.Vector3.Cross(v3, v4);
  66909. vn = vn.normalize();
  66910. uvs.push(ulength / bounds.width, 0);
  66911. uvs.push(ulength / bounds.width, 1);
  66912. ulength += v3.length();
  66913. uvs.push((ulength / bounds.width), 0);
  66914. uvs.push((ulength / bounds.width), 1);
  66915. if (!flip) {
  66916. normals.push(-vn.x, -vn.y, -vn.z);
  66917. normals.push(-vn.x, -vn.y, -vn.z);
  66918. normals.push(-vn.x, -vn.y, -vn.z);
  66919. normals.push(-vn.x, -vn.y, -vn.z);
  66920. indices.push(StartIndex);
  66921. indices.push(StartIndex + 1);
  66922. indices.push(StartIndex + 2);
  66923. indices.push(StartIndex + 1);
  66924. indices.push(StartIndex + 3);
  66925. indices.push(StartIndex + 2);
  66926. }
  66927. else {
  66928. normals.push(vn.x, vn.y, vn.z);
  66929. normals.push(vn.x, vn.y, vn.z);
  66930. normals.push(vn.x, vn.y, vn.z);
  66931. normals.push(vn.x, vn.y, vn.z);
  66932. indices.push(StartIndex);
  66933. indices.push(StartIndex + 2);
  66934. indices.push(StartIndex + 1);
  66935. indices.push(StartIndex + 1);
  66936. indices.push(StartIndex + 2);
  66937. indices.push(StartIndex + 3);
  66938. }
  66939. StartIndex += 4;
  66940. }
  66941. ;
  66942. };
  66943. return PolygonMeshBuilder;
  66944. }());
  66945. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66946. })(BABYLON || (BABYLON = {}));
  66947. //# sourceMappingURL=babylon.polygonMesh.js.map
  66948. var BABYLON;
  66949. (function (BABYLON) {
  66950. // Unique ID when we import meshes from Babylon to CSG
  66951. var currentCSGMeshId = 0;
  66952. // # class Vertex
  66953. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66954. // one to provide additional features like texture coordinates and vertex
  66955. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66956. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66957. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66958. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66959. // is not used anywhere else.
  66960. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66961. var Vertex = /** @class */ (function () {
  66962. function Vertex(pos, normal, uv) {
  66963. this.pos = pos;
  66964. this.normal = normal;
  66965. this.uv = uv;
  66966. }
  66967. Vertex.prototype.clone = function () {
  66968. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  66969. };
  66970. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  66971. // orientation of a polygon is flipped.
  66972. Vertex.prototype.flip = function () {
  66973. this.normal = this.normal.scale(-1);
  66974. };
  66975. // Create a new vertex between this vertex and `other` by linearly
  66976. // interpolating all properties using a parameter of `t`. Subclasses should
  66977. // override this to interpolate additional properties.
  66978. Vertex.prototype.interpolate = function (other, t) {
  66979. 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));
  66980. };
  66981. return Vertex;
  66982. }());
  66983. // # class Plane
  66984. // Represents a plane in 3D space.
  66985. var Plane = /** @class */ (function () {
  66986. function Plane(normal, w) {
  66987. this.normal = normal;
  66988. this.w = w;
  66989. }
  66990. Plane.FromPoints = function (a, b, c) {
  66991. var v0 = c.subtract(a);
  66992. var v1 = b.subtract(a);
  66993. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  66994. return null;
  66995. }
  66996. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  66997. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  66998. };
  66999. Plane.prototype.clone = function () {
  67000. return new Plane(this.normal.clone(), this.w);
  67001. };
  67002. Plane.prototype.flip = function () {
  67003. this.normal.scaleInPlace(-1);
  67004. this.w = -this.w;
  67005. };
  67006. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67007. // fragments in the appropriate lists. Coplanar polygons go into either
  67008. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67009. // respect to this plane. Polygons in front or in back of this plane go into
  67010. // either `front` or `back`.
  67011. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67012. var COPLANAR = 0;
  67013. var FRONT = 1;
  67014. var BACK = 2;
  67015. var SPANNING = 3;
  67016. // Classify each point as well as the entire polygon into one of the above
  67017. // four classes.
  67018. var polygonType = 0;
  67019. var types = [];
  67020. var i;
  67021. var t;
  67022. for (i = 0; i < polygon.vertices.length; i++) {
  67023. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67024. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67025. polygonType |= type;
  67026. types.push(type);
  67027. }
  67028. // Put the polygon in the correct list, splitting it when necessary.
  67029. switch (polygonType) {
  67030. case COPLANAR:
  67031. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67032. break;
  67033. case FRONT:
  67034. front.push(polygon);
  67035. break;
  67036. case BACK:
  67037. back.push(polygon);
  67038. break;
  67039. case SPANNING:
  67040. var f = [], b = [];
  67041. for (i = 0; i < polygon.vertices.length; i++) {
  67042. var j = (i + 1) % polygon.vertices.length;
  67043. var ti = types[i], tj = types[j];
  67044. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67045. if (ti !== BACK)
  67046. f.push(vi);
  67047. if (ti !== FRONT)
  67048. b.push(ti !== BACK ? vi.clone() : vi);
  67049. if ((ti | tj) === SPANNING) {
  67050. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67051. var v = vi.interpolate(vj, t);
  67052. f.push(v);
  67053. b.push(v.clone());
  67054. }
  67055. }
  67056. var poly;
  67057. if (f.length >= 3) {
  67058. poly = new Polygon(f, polygon.shared);
  67059. if (poly.plane)
  67060. front.push(poly);
  67061. }
  67062. if (b.length >= 3) {
  67063. poly = new Polygon(b, polygon.shared);
  67064. if (poly.plane)
  67065. back.push(poly);
  67066. }
  67067. break;
  67068. }
  67069. };
  67070. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67071. // point is on the plane.
  67072. Plane.EPSILON = 1e-5;
  67073. return Plane;
  67074. }());
  67075. // # class Polygon
  67076. // Represents a convex polygon. The vertices used to initialize a polygon must
  67077. // be coplanar and form a convex loop.
  67078. //
  67079. // Each convex polygon has a `shared` property, which is shared between all
  67080. // polygons that are clones of each other or were split from the same polygon.
  67081. // This can be used to define per-polygon properties (such as surface color).
  67082. var Polygon = /** @class */ (function () {
  67083. function Polygon(vertices, shared) {
  67084. this.vertices = vertices;
  67085. this.shared = shared;
  67086. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67087. }
  67088. Polygon.prototype.clone = function () {
  67089. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67090. return new Polygon(vertices, this.shared);
  67091. };
  67092. Polygon.prototype.flip = function () {
  67093. this.vertices.reverse().map(function (v) { v.flip(); });
  67094. this.plane.flip();
  67095. };
  67096. return Polygon;
  67097. }());
  67098. // # class Node
  67099. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67100. // by picking a polygon to split along. That polygon (and all other coplanar
  67101. // polygons) are added directly to that node and the other polygons are added to
  67102. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67103. // no distinction between internal and leaf nodes.
  67104. var Node = /** @class */ (function () {
  67105. function Node(polygons) {
  67106. this.plane = null;
  67107. this.front = null;
  67108. this.back = null;
  67109. this.polygons = new Array();
  67110. if (polygons) {
  67111. this.build(polygons);
  67112. }
  67113. }
  67114. Node.prototype.clone = function () {
  67115. var node = new Node();
  67116. node.plane = this.plane && this.plane.clone();
  67117. node.front = this.front && this.front.clone();
  67118. node.back = this.back && this.back.clone();
  67119. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67120. return node;
  67121. };
  67122. // Convert solid space to empty space and empty space to solid space.
  67123. Node.prototype.invert = function () {
  67124. for (var i = 0; i < this.polygons.length; i++) {
  67125. this.polygons[i].flip();
  67126. }
  67127. if (this.plane) {
  67128. this.plane.flip();
  67129. }
  67130. if (this.front) {
  67131. this.front.invert();
  67132. }
  67133. if (this.back) {
  67134. this.back.invert();
  67135. }
  67136. var temp = this.front;
  67137. this.front = this.back;
  67138. this.back = temp;
  67139. };
  67140. // Recursively remove all polygons in `polygons` that are inside this BSP
  67141. // tree.
  67142. Node.prototype.clipPolygons = function (polygons) {
  67143. if (!this.plane)
  67144. return polygons.slice();
  67145. var front = new Array(), back = new Array();
  67146. for (var i = 0; i < polygons.length; i++) {
  67147. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67148. }
  67149. if (this.front) {
  67150. front = this.front.clipPolygons(front);
  67151. }
  67152. if (this.back) {
  67153. back = this.back.clipPolygons(back);
  67154. }
  67155. else {
  67156. back = [];
  67157. }
  67158. return front.concat(back);
  67159. };
  67160. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67161. // `bsp`.
  67162. Node.prototype.clipTo = function (bsp) {
  67163. this.polygons = bsp.clipPolygons(this.polygons);
  67164. if (this.front)
  67165. this.front.clipTo(bsp);
  67166. if (this.back)
  67167. this.back.clipTo(bsp);
  67168. };
  67169. // Return a list of all polygons in this BSP tree.
  67170. Node.prototype.allPolygons = function () {
  67171. var polygons = this.polygons.slice();
  67172. if (this.front)
  67173. polygons = polygons.concat(this.front.allPolygons());
  67174. if (this.back)
  67175. polygons = polygons.concat(this.back.allPolygons());
  67176. return polygons;
  67177. };
  67178. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67179. // new polygons are filtered down to the bottom of the tree and become new
  67180. // nodes there. Each set of polygons is partitioned using the first polygon
  67181. // (no heuristic is used to pick a good split).
  67182. Node.prototype.build = function (polygons) {
  67183. if (!polygons.length)
  67184. return;
  67185. if (!this.plane)
  67186. this.plane = polygons[0].plane.clone();
  67187. var front = new Array(), back = new Array();
  67188. for (var i = 0; i < polygons.length; i++) {
  67189. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67190. }
  67191. if (front.length) {
  67192. if (!this.front)
  67193. this.front = new Node();
  67194. this.front.build(front);
  67195. }
  67196. if (back.length) {
  67197. if (!this.back)
  67198. this.back = new Node();
  67199. this.back.build(back);
  67200. }
  67201. };
  67202. return Node;
  67203. }());
  67204. var CSG = /** @class */ (function () {
  67205. function CSG() {
  67206. this.polygons = new Array();
  67207. }
  67208. // Convert BABYLON.Mesh to BABYLON.CSG
  67209. CSG.FromMesh = function (mesh) {
  67210. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67211. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67212. if (mesh instanceof BABYLON.Mesh) {
  67213. mesh.computeWorldMatrix(true);
  67214. matrix = mesh.getWorldMatrix();
  67215. meshPosition = mesh.position.clone();
  67216. meshRotation = mesh.rotation.clone();
  67217. if (mesh.rotationQuaternion) {
  67218. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67219. }
  67220. meshScaling = mesh.scaling.clone();
  67221. }
  67222. else {
  67223. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67224. }
  67225. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67226. var subMeshes = mesh.subMeshes;
  67227. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67228. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67229. vertices = [];
  67230. for (var j = 0; j < 3; j++) {
  67231. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67232. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67233. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67234. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67235. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67236. vertex = new Vertex(position, normal, uv);
  67237. vertices.push(vertex);
  67238. }
  67239. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67240. // To handle the case of degenerated triangle
  67241. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67242. if (polygon.plane)
  67243. polygons.push(polygon);
  67244. }
  67245. }
  67246. var csg = CSG.FromPolygons(polygons);
  67247. csg.matrix = matrix;
  67248. csg.position = meshPosition;
  67249. csg.rotation = meshRotation;
  67250. csg.scaling = meshScaling;
  67251. csg.rotationQuaternion = meshRotationQuaternion;
  67252. currentCSGMeshId++;
  67253. return csg;
  67254. };
  67255. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67256. CSG.FromPolygons = function (polygons) {
  67257. var csg = new CSG();
  67258. csg.polygons = polygons;
  67259. return csg;
  67260. };
  67261. CSG.prototype.clone = function () {
  67262. var csg = new CSG();
  67263. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67264. csg.copyTransformAttributes(this);
  67265. return csg;
  67266. };
  67267. CSG.prototype.union = function (csg) {
  67268. var a = new Node(this.clone().polygons);
  67269. var b = new Node(csg.clone().polygons);
  67270. a.clipTo(b);
  67271. b.clipTo(a);
  67272. b.invert();
  67273. b.clipTo(a);
  67274. b.invert();
  67275. a.build(b.allPolygons());
  67276. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67277. };
  67278. CSG.prototype.unionInPlace = function (csg) {
  67279. var a = new Node(this.polygons);
  67280. var b = new Node(csg.polygons);
  67281. a.clipTo(b);
  67282. b.clipTo(a);
  67283. b.invert();
  67284. b.clipTo(a);
  67285. b.invert();
  67286. a.build(b.allPolygons());
  67287. this.polygons = a.allPolygons();
  67288. };
  67289. CSG.prototype.subtract = function (csg) {
  67290. var a = new Node(this.clone().polygons);
  67291. var b = new Node(csg.clone().polygons);
  67292. a.invert();
  67293. a.clipTo(b);
  67294. b.clipTo(a);
  67295. b.invert();
  67296. b.clipTo(a);
  67297. b.invert();
  67298. a.build(b.allPolygons());
  67299. a.invert();
  67300. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67301. };
  67302. CSG.prototype.subtractInPlace = function (csg) {
  67303. var a = new Node(this.polygons);
  67304. var b = new Node(csg.polygons);
  67305. a.invert();
  67306. a.clipTo(b);
  67307. b.clipTo(a);
  67308. b.invert();
  67309. b.clipTo(a);
  67310. b.invert();
  67311. a.build(b.allPolygons());
  67312. a.invert();
  67313. this.polygons = a.allPolygons();
  67314. };
  67315. CSG.prototype.intersect = function (csg) {
  67316. var a = new Node(this.clone().polygons);
  67317. var b = new Node(csg.clone().polygons);
  67318. a.invert();
  67319. b.clipTo(a);
  67320. b.invert();
  67321. a.clipTo(b);
  67322. b.clipTo(a);
  67323. a.build(b.allPolygons());
  67324. a.invert();
  67325. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67326. };
  67327. CSG.prototype.intersectInPlace = function (csg) {
  67328. var a = new Node(this.polygons);
  67329. var b = new Node(csg.polygons);
  67330. a.invert();
  67331. b.clipTo(a);
  67332. b.invert();
  67333. a.clipTo(b);
  67334. b.clipTo(a);
  67335. a.build(b.allPolygons());
  67336. a.invert();
  67337. this.polygons = a.allPolygons();
  67338. };
  67339. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67340. // not modified.
  67341. CSG.prototype.inverse = function () {
  67342. var csg = this.clone();
  67343. csg.inverseInPlace();
  67344. return csg;
  67345. };
  67346. CSG.prototype.inverseInPlace = function () {
  67347. this.polygons.map(function (p) { p.flip(); });
  67348. };
  67349. // This is used to keep meshes transformations so they can be restored
  67350. // when we build back a Babylon Mesh
  67351. // NB : All CSG operations are performed in world coordinates
  67352. CSG.prototype.copyTransformAttributes = function (csg) {
  67353. this.matrix = csg.matrix;
  67354. this.position = csg.position;
  67355. this.rotation = csg.rotation;
  67356. this.scaling = csg.scaling;
  67357. this.rotationQuaternion = csg.rotationQuaternion;
  67358. return this;
  67359. };
  67360. // Build Raw mesh from CSG
  67361. // Coordinates here are in world space
  67362. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67363. var matrix = this.matrix.clone();
  67364. matrix.invert();
  67365. 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;
  67366. if (keepSubMeshes) {
  67367. // Sort Polygons, since subMeshes are indices range
  67368. polygons.sort(function (a, b) {
  67369. if (a.shared.meshId === b.shared.meshId) {
  67370. return a.shared.subMeshId - b.shared.subMeshId;
  67371. }
  67372. else {
  67373. return a.shared.meshId - b.shared.meshId;
  67374. }
  67375. });
  67376. }
  67377. for (var i = 0, il = polygons.length; i < il; i++) {
  67378. polygon = polygons[i];
  67379. // Building SubMeshes
  67380. if (!subMesh_dict[polygon.shared.meshId]) {
  67381. subMesh_dict[polygon.shared.meshId] = {};
  67382. }
  67383. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67384. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67385. indexStart: +Infinity,
  67386. indexEnd: -Infinity,
  67387. materialIndex: polygon.shared.materialIndex
  67388. };
  67389. }
  67390. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67391. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67392. polygonIndices[0] = 0;
  67393. polygonIndices[1] = j - 1;
  67394. polygonIndices[2] = j;
  67395. for (var k = 0; k < 3; k++) {
  67396. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67397. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67398. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67399. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67400. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67401. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67402. // Check if 2 points can be merged
  67403. if (!(typeof vertex_idx !== 'undefined' &&
  67404. normals[vertex_idx * 3] === localNormal.x &&
  67405. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67406. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67407. uvs[vertex_idx * 2] === uv.x &&
  67408. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67409. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67410. uvs.push(uv.x, uv.y);
  67411. normals.push(normal.x, normal.y, normal.z);
  67412. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67413. }
  67414. indices.push(vertex_idx);
  67415. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67416. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67417. currentIndex++;
  67418. }
  67419. }
  67420. }
  67421. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67422. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67423. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67424. mesh.setIndices(indices, null);
  67425. if (keepSubMeshes) {
  67426. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67427. var materialIndexOffset = 0, materialMaxIndex;
  67428. mesh.subMeshes = new Array();
  67429. for (var m in subMesh_dict) {
  67430. materialMaxIndex = -1;
  67431. for (var sm in subMesh_dict[m]) {
  67432. subMesh_obj = subMesh_dict[m][sm];
  67433. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67434. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67435. }
  67436. materialIndexOffset += ++materialMaxIndex;
  67437. }
  67438. }
  67439. return mesh;
  67440. };
  67441. // Build Mesh from CSG taking material and transforms into account
  67442. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67443. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67444. mesh.material = material;
  67445. mesh.position.copyFrom(this.position);
  67446. mesh.rotation.copyFrom(this.rotation);
  67447. if (this.rotationQuaternion) {
  67448. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67449. }
  67450. mesh.scaling.copyFrom(this.scaling);
  67451. mesh.computeWorldMatrix(true);
  67452. return mesh;
  67453. };
  67454. return CSG;
  67455. }());
  67456. BABYLON.CSG = CSG;
  67457. })(BABYLON || (BABYLON = {}));
  67458. //# sourceMappingURL=babylon.csg.js.map
  67459. var BABYLON;
  67460. (function (BABYLON) {
  67461. var LensFlare = /** @class */ (function () {
  67462. function LensFlare(size, position, color, imgUrl, system) {
  67463. this.size = size;
  67464. this.position = position;
  67465. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67466. this.color = color || new BABYLON.Color3(1, 1, 1);
  67467. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67468. this._system = system;
  67469. system.lensFlares.push(this);
  67470. }
  67471. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67472. return new LensFlare(size, position, color, imgUrl, system);
  67473. };
  67474. LensFlare.prototype.dispose = function () {
  67475. if (this.texture) {
  67476. this.texture.dispose();
  67477. }
  67478. // Remove from scene
  67479. var index = this._system.lensFlares.indexOf(this);
  67480. this._system.lensFlares.splice(index, 1);
  67481. };
  67482. ;
  67483. return LensFlare;
  67484. }());
  67485. BABYLON.LensFlare = LensFlare;
  67486. })(BABYLON || (BABYLON = {}));
  67487. //# sourceMappingURL=babylon.lensFlare.js.map
  67488. var BABYLON;
  67489. (function (BABYLON) {
  67490. var LensFlareSystem = /** @class */ (function () {
  67491. function LensFlareSystem(name, emitter, scene) {
  67492. this.name = name;
  67493. this.lensFlares = new Array();
  67494. this.borderLimit = 300;
  67495. this.viewportBorder = 0;
  67496. this.layerMask = 0x0FFFFFFF;
  67497. this._vertexBuffers = {};
  67498. this._isEnabled = true;
  67499. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67500. this._emitter = emitter;
  67501. this.id = name;
  67502. scene.lensFlareSystems.push(this);
  67503. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67504. var engine = scene.getEngine();
  67505. // VBO
  67506. var vertices = [];
  67507. vertices.push(1, 1);
  67508. vertices.push(-1, 1);
  67509. vertices.push(-1, -1);
  67510. vertices.push(1, -1);
  67511. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67512. // Indices
  67513. var indices = [];
  67514. indices.push(0);
  67515. indices.push(1);
  67516. indices.push(2);
  67517. indices.push(0);
  67518. indices.push(2);
  67519. indices.push(3);
  67520. this._indexBuffer = engine.createIndexBuffer(indices);
  67521. // Effects
  67522. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67523. }
  67524. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67525. get: function () {
  67526. return this._isEnabled;
  67527. },
  67528. set: function (value) {
  67529. this._isEnabled = value;
  67530. },
  67531. enumerable: true,
  67532. configurable: true
  67533. });
  67534. LensFlareSystem.prototype.getScene = function () {
  67535. return this._scene;
  67536. };
  67537. LensFlareSystem.prototype.getEmitter = function () {
  67538. return this._emitter;
  67539. };
  67540. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67541. this._emitter = newEmitter;
  67542. };
  67543. LensFlareSystem.prototype.getEmitterPosition = function () {
  67544. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67545. };
  67546. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67547. var position = this.getEmitterPosition();
  67548. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67549. this._positionX = position.x;
  67550. this._positionY = position.y;
  67551. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67552. if (this.viewportBorder > 0) {
  67553. globalViewport.x -= this.viewportBorder;
  67554. globalViewport.y -= this.viewportBorder;
  67555. globalViewport.width += this.viewportBorder * 2;
  67556. globalViewport.height += this.viewportBorder * 2;
  67557. position.x += this.viewportBorder;
  67558. position.y += this.viewportBorder;
  67559. this._positionX += this.viewportBorder;
  67560. this._positionY += this.viewportBorder;
  67561. }
  67562. if (position.z > 0) {
  67563. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67564. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67565. return true;
  67566. }
  67567. return true;
  67568. }
  67569. return false;
  67570. };
  67571. LensFlareSystem.prototype._isVisible = function () {
  67572. if (!this._isEnabled || !this._scene.activeCamera) {
  67573. return false;
  67574. }
  67575. var emitterPosition = this.getEmitterPosition();
  67576. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67577. var distance = direction.length();
  67578. direction.normalize();
  67579. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67580. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67581. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67582. };
  67583. LensFlareSystem.prototype.render = function () {
  67584. if (!this._effect.isReady() || !this._scene.activeCamera)
  67585. return false;
  67586. var engine = this._scene.getEngine();
  67587. var viewport = this._scene.activeCamera.viewport;
  67588. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67589. // Position
  67590. if (!this.computeEffectivePosition(globalViewport)) {
  67591. return false;
  67592. }
  67593. // Visibility
  67594. if (!this._isVisible()) {
  67595. return false;
  67596. }
  67597. // Intensity
  67598. var awayX;
  67599. var awayY;
  67600. if (this._positionX < this.borderLimit + globalViewport.x) {
  67601. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67602. }
  67603. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67604. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67605. }
  67606. else {
  67607. awayX = 0;
  67608. }
  67609. if (this._positionY < this.borderLimit + globalViewport.y) {
  67610. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67611. }
  67612. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67613. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67614. }
  67615. else {
  67616. awayY = 0;
  67617. }
  67618. var away = (awayX > awayY) ? awayX : awayY;
  67619. away -= this.viewportBorder;
  67620. if (away > this.borderLimit) {
  67621. away = this.borderLimit;
  67622. }
  67623. var intensity = 1.0 - (away / this.borderLimit);
  67624. if (intensity < 0) {
  67625. return false;
  67626. }
  67627. if (intensity > 1.0) {
  67628. intensity = 1.0;
  67629. }
  67630. if (this.viewportBorder > 0) {
  67631. globalViewport.x += this.viewportBorder;
  67632. globalViewport.y += this.viewportBorder;
  67633. globalViewport.width -= this.viewportBorder * 2;
  67634. globalViewport.height -= this.viewportBorder * 2;
  67635. this._positionX -= this.viewportBorder;
  67636. this._positionY -= this.viewportBorder;
  67637. }
  67638. // Position
  67639. var centerX = globalViewport.x + globalViewport.width / 2;
  67640. var centerY = globalViewport.y + globalViewport.height / 2;
  67641. var distX = centerX - this._positionX;
  67642. var distY = centerY - this._positionY;
  67643. // Effects
  67644. engine.enableEffect(this._effect);
  67645. engine.setState(false);
  67646. engine.setDepthBuffer(false);
  67647. // VBOs
  67648. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67649. // Flares
  67650. for (var index = 0; index < this.lensFlares.length; index++) {
  67651. var flare = this.lensFlares[index];
  67652. engine.setAlphaMode(flare.alphaMode);
  67653. var x = centerX - (distX * flare.position);
  67654. var y = centerY - (distY * flare.position);
  67655. var cw = flare.size;
  67656. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67657. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67658. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67659. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67660. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67661. // Texture
  67662. this._effect.setTexture("textureSampler", flare.texture);
  67663. // Color
  67664. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67665. // Draw order
  67666. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67667. }
  67668. engine.setDepthBuffer(true);
  67669. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67670. return true;
  67671. };
  67672. LensFlareSystem.prototype.dispose = function () {
  67673. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67674. if (vertexBuffer) {
  67675. vertexBuffer.dispose();
  67676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67677. }
  67678. if (this._indexBuffer) {
  67679. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67680. this._indexBuffer = null;
  67681. }
  67682. while (this.lensFlares.length) {
  67683. this.lensFlares[0].dispose();
  67684. }
  67685. // Remove from scene
  67686. var index = this._scene.lensFlareSystems.indexOf(this);
  67687. this._scene.lensFlareSystems.splice(index, 1);
  67688. };
  67689. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67690. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67691. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67692. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67693. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67694. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67695. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67696. var parsedFlare = parsedLensFlareSystem.flares[index];
  67697. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67698. }
  67699. return lensFlareSystem;
  67700. };
  67701. LensFlareSystem.prototype.serialize = function () {
  67702. var serializationObject = {};
  67703. serializationObject.id = this.id;
  67704. serializationObject.name = this.name;
  67705. serializationObject.emitterId = this.getEmitter().id;
  67706. serializationObject.borderLimit = this.borderLimit;
  67707. serializationObject.flares = [];
  67708. for (var index = 0; index < this.lensFlares.length; index++) {
  67709. var flare = this.lensFlares[index];
  67710. serializationObject.flares.push({
  67711. size: flare.size,
  67712. position: flare.position,
  67713. color: flare.color.asArray(),
  67714. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67715. });
  67716. }
  67717. return serializationObject;
  67718. };
  67719. return LensFlareSystem;
  67720. }());
  67721. BABYLON.LensFlareSystem = LensFlareSystem;
  67722. })(BABYLON || (BABYLON = {}));
  67723. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67724. var BABYLON;
  67725. (function (BABYLON) {
  67726. /**
  67727. * This is a holder class for the physics joint created by the physics plugin.
  67728. * It holds a set of functions to control the underlying joint.
  67729. */
  67730. var PhysicsJoint = /** @class */ (function () {
  67731. function PhysicsJoint(type, jointData) {
  67732. this.type = type;
  67733. this.jointData = jointData;
  67734. jointData.nativeParams = jointData.nativeParams || {};
  67735. }
  67736. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67737. get: function () {
  67738. return this._physicsJoint;
  67739. },
  67740. set: function (newJoint) {
  67741. if (this._physicsJoint) {
  67742. //remove from the wolrd
  67743. }
  67744. this._physicsJoint = newJoint;
  67745. },
  67746. enumerable: true,
  67747. configurable: true
  67748. });
  67749. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67750. set: function (physicsPlugin) {
  67751. this._physicsPlugin = physicsPlugin;
  67752. },
  67753. enumerable: true,
  67754. configurable: true
  67755. });
  67756. /**
  67757. * Execute a function that is physics-plugin specific.
  67758. * @param {Function} func the function that will be executed.
  67759. * It accepts two parameters: the physics world and the physics joint.
  67760. */
  67761. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67762. func(this._physicsPlugin.world, this._physicsJoint);
  67763. };
  67764. //TODO check if the native joints are the same
  67765. //Joint Types
  67766. PhysicsJoint.DistanceJoint = 0;
  67767. PhysicsJoint.HingeJoint = 1;
  67768. PhysicsJoint.BallAndSocketJoint = 2;
  67769. PhysicsJoint.WheelJoint = 3;
  67770. PhysicsJoint.SliderJoint = 4;
  67771. //OIMO
  67772. PhysicsJoint.PrismaticJoint = 5;
  67773. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67774. PhysicsJoint.UniversalJoint = 6;
  67775. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67776. //Cannon
  67777. //Similar to a Ball-Joint. Different in params
  67778. PhysicsJoint.PointToPointJoint = 8;
  67779. //Cannon only at the moment
  67780. PhysicsJoint.SpringJoint = 9;
  67781. PhysicsJoint.LockJoint = 10;
  67782. return PhysicsJoint;
  67783. }());
  67784. BABYLON.PhysicsJoint = PhysicsJoint;
  67785. /**
  67786. * A class representing a physics distance joint.
  67787. */
  67788. var DistanceJoint = /** @class */ (function (_super) {
  67789. __extends(DistanceJoint, _super);
  67790. function DistanceJoint(jointData) {
  67791. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67792. }
  67793. /**
  67794. * Update the predefined distance.
  67795. */
  67796. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67797. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67798. };
  67799. return DistanceJoint;
  67800. }(PhysicsJoint));
  67801. BABYLON.DistanceJoint = DistanceJoint;
  67802. var MotorEnabledJoint = /** @class */ (function (_super) {
  67803. __extends(MotorEnabledJoint, _super);
  67804. function MotorEnabledJoint(type, jointData) {
  67805. return _super.call(this, type, jointData) || this;
  67806. }
  67807. /**
  67808. * Set the motor values.
  67809. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67810. * @param {number} force the force to apply
  67811. * @param {number} maxForce max force for this motor.
  67812. */
  67813. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67814. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67815. };
  67816. /**
  67817. * Set the motor's limits.
  67818. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67819. */
  67820. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67821. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67822. };
  67823. return MotorEnabledJoint;
  67824. }(PhysicsJoint));
  67825. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67826. /**
  67827. * This class represents a single hinge physics joint
  67828. */
  67829. var HingeJoint = /** @class */ (function (_super) {
  67830. __extends(HingeJoint, _super);
  67831. function HingeJoint(jointData) {
  67832. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67833. }
  67834. /**
  67835. * Set the motor values.
  67836. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67837. * @param {number} force the force to apply
  67838. * @param {number} maxForce max force for this motor.
  67839. */
  67840. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67841. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67842. };
  67843. /**
  67844. * Set the motor's limits.
  67845. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67846. */
  67847. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67848. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67849. };
  67850. return HingeJoint;
  67851. }(MotorEnabledJoint));
  67852. BABYLON.HingeJoint = HingeJoint;
  67853. /**
  67854. * This class represents a dual hinge physics joint (same as wheel joint)
  67855. */
  67856. var Hinge2Joint = /** @class */ (function (_super) {
  67857. __extends(Hinge2Joint, _super);
  67858. function Hinge2Joint(jointData) {
  67859. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67860. }
  67861. /**
  67862. * Set the motor values.
  67863. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67864. * @param {number} force the force to apply
  67865. * @param {number} maxForce max force for this motor.
  67866. * @param {motorIndex} the motor's index, 0 or 1.
  67867. */
  67868. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67869. if (motorIndex === void 0) { motorIndex = 0; }
  67870. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67871. };
  67872. /**
  67873. * Set the motor limits.
  67874. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67875. * @param {number} upperLimit the upper limit
  67876. * @param {number} lowerLimit lower limit
  67877. * @param {motorIndex} the motor's index, 0 or 1.
  67878. */
  67879. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67880. if (motorIndex === void 0) { motorIndex = 0; }
  67881. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67882. };
  67883. return Hinge2Joint;
  67884. }(MotorEnabledJoint));
  67885. BABYLON.Hinge2Joint = Hinge2Joint;
  67886. })(BABYLON || (BABYLON = {}));
  67887. //# sourceMappingURL=babylon.physicsJoint.js.map
  67888. var BABYLON;
  67889. (function (BABYLON) {
  67890. var PhysicsImpostor = /** @class */ (function () {
  67891. function PhysicsImpostor(object, type, _options, _scene) {
  67892. if (_options === void 0) { _options = { mass: 0 }; }
  67893. var _this = this;
  67894. this.object = object;
  67895. this.type = type;
  67896. this._options = _options;
  67897. this._scene = _scene;
  67898. this._bodyUpdateRequired = false;
  67899. this._onBeforePhysicsStepCallbacks = new Array();
  67900. this._onAfterPhysicsStepCallbacks = new Array();
  67901. this._onPhysicsCollideCallbacks = [];
  67902. this._deltaPosition = BABYLON.Vector3.Zero();
  67903. this._isDisposed = false;
  67904. //temp variables for parent rotation calculations
  67905. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67906. this._tmpQuat = new BABYLON.Quaternion();
  67907. this._tmpQuat2 = new BABYLON.Quaternion();
  67908. /**
  67909. * this function is executed by the physics engine.
  67910. */
  67911. this.beforeStep = function () {
  67912. if (!_this._physicsEngine) {
  67913. return;
  67914. }
  67915. _this.object.translate(_this._deltaPosition, -1);
  67916. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67917. _this.object.computeWorldMatrix(false);
  67918. if (_this.object.parent && _this.object.rotationQuaternion) {
  67919. _this.getParentsRotation();
  67920. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67921. }
  67922. else {
  67923. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67924. }
  67925. if (!_this._options.disableBidirectionalTransformation) {
  67926. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67927. }
  67928. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67929. func(_this);
  67930. });
  67931. };
  67932. /**
  67933. * this function is executed by the physics engine.
  67934. */
  67935. this.afterStep = function () {
  67936. if (!_this._physicsEngine) {
  67937. return;
  67938. }
  67939. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67940. func(_this);
  67941. });
  67942. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67943. // object has now its world rotation. needs to be converted to local.
  67944. if (_this.object.parent && _this.object.rotationQuaternion) {
  67945. _this.getParentsRotation();
  67946. _this._tmpQuat.conjugateInPlace();
  67947. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67948. }
  67949. // take the position set and make it the absolute position of this object.
  67950. _this.object.setAbsolutePosition(_this.object.position);
  67951. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67952. _this.object.translate(_this._deltaPosition, 1);
  67953. };
  67954. /**
  67955. * Legacy collision detection event support
  67956. */
  67957. this.onCollideEvent = null;
  67958. //event and body object due to cannon's event-based architecture.
  67959. this.onCollide = function (e) {
  67960. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67961. return;
  67962. }
  67963. if (!_this._physicsEngine) {
  67964. return;
  67965. }
  67966. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  67967. if (otherImpostor) {
  67968. // Legacy collision detection event support
  67969. if (_this.onCollideEvent) {
  67970. _this.onCollideEvent(_this, otherImpostor);
  67971. }
  67972. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  67973. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  67974. }).forEach(function (obj) {
  67975. obj.callback(_this, otherImpostor);
  67976. });
  67977. }
  67978. };
  67979. //sanity check!
  67980. if (!this.object) {
  67981. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  67982. return;
  67983. }
  67984. //legacy support for old syntax.
  67985. if (!this._scene && object.getScene) {
  67986. this._scene = object.getScene();
  67987. }
  67988. if (!this._scene) {
  67989. return;
  67990. }
  67991. this._physicsEngine = this._scene.getPhysicsEngine();
  67992. if (!this._physicsEngine) {
  67993. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  67994. }
  67995. else {
  67996. //set the object's quaternion, if not set
  67997. if (!this.object.rotationQuaternion) {
  67998. if (this.object.rotation) {
  67999. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68000. }
  68001. else {
  68002. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68003. }
  68004. }
  68005. //default options params
  68006. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68007. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68008. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68009. this._joints = [];
  68010. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68011. if (!this.object.parent || this._options.ignoreParent) {
  68012. this._init();
  68013. }
  68014. else if (this.object.parent.physicsImpostor) {
  68015. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68016. }
  68017. }
  68018. }
  68019. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68020. get: function () {
  68021. return this._isDisposed;
  68022. },
  68023. enumerable: true,
  68024. configurable: true
  68025. });
  68026. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68027. get: function () {
  68028. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68029. },
  68030. set: function (value) {
  68031. this.setMass(value);
  68032. },
  68033. enumerable: true,
  68034. configurable: true
  68035. });
  68036. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68037. get: function () {
  68038. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68039. },
  68040. set: function (value) {
  68041. if (!this._physicsEngine) {
  68042. return;
  68043. }
  68044. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68045. },
  68046. enumerable: true,
  68047. configurable: true
  68048. });
  68049. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68050. get: function () {
  68051. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68052. },
  68053. set: function (value) {
  68054. if (!this._physicsEngine) {
  68055. return;
  68056. }
  68057. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68058. },
  68059. enumerable: true,
  68060. configurable: true
  68061. });
  68062. /**
  68063. * This function will completly initialize this impostor.
  68064. * It will create a new body - but only if this mesh has no parent.
  68065. * If it has, this impostor will not be used other than to define the impostor
  68066. * of the child mesh.
  68067. */
  68068. PhysicsImpostor.prototype._init = function () {
  68069. if (!this._physicsEngine) {
  68070. return;
  68071. }
  68072. this._physicsEngine.removeImpostor(this);
  68073. this.physicsBody = null;
  68074. this._parent = this._parent || this._getPhysicsParent();
  68075. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68076. this._physicsEngine.addImpostor(this);
  68077. }
  68078. };
  68079. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68080. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68081. var parentMesh = this.object.parent;
  68082. return parentMesh.physicsImpostor;
  68083. }
  68084. return null;
  68085. };
  68086. /**
  68087. * Should a new body be generated.
  68088. */
  68089. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68090. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68091. };
  68092. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68093. this.forceUpdate();
  68094. };
  68095. /**
  68096. * Force a regeneration of this or the parent's impostor's body.
  68097. * Use under cautious - This will remove all joints already implemented.
  68098. */
  68099. PhysicsImpostor.prototype.forceUpdate = function () {
  68100. this._init();
  68101. if (this.parent && !this._options.ignoreParent) {
  68102. this.parent.forceUpdate();
  68103. }
  68104. };
  68105. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68106. /*public get mesh(): AbstractMesh {
  68107. return this._mesh;
  68108. }*/
  68109. /**
  68110. * Gets the body that holds this impostor. Either its own, or its parent.
  68111. */
  68112. get: function () {
  68113. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68114. },
  68115. /**
  68116. * Set the physics body. Used mainly by the physics engine/plugin
  68117. */
  68118. set: function (physicsBody) {
  68119. if (this._physicsBody && this._physicsEngine) {
  68120. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68121. }
  68122. this._physicsBody = physicsBody;
  68123. this.resetUpdateFlags();
  68124. },
  68125. enumerable: true,
  68126. configurable: true
  68127. });
  68128. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68129. get: function () {
  68130. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68131. },
  68132. set: function (value) {
  68133. this._parent = value;
  68134. },
  68135. enumerable: true,
  68136. configurable: true
  68137. });
  68138. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68139. this._bodyUpdateRequired = false;
  68140. };
  68141. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68142. if (this.object.getBoundingInfo) {
  68143. var q = this.object.rotationQuaternion;
  68144. //reset rotation
  68145. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68146. //calculate the world matrix with no rotation
  68147. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68148. var boundingInfo = this.object.getBoundingInfo();
  68149. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68150. //bring back the rotation
  68151. this.object.rotationQuaternion = q;
  68152. //calculate the world matrix with the new rotation
  68153. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68154. return size;
  68155. }
  68156. else {
  68157. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68158. }
  68159. };
  68160. PhysicsImpostor.prototype.getObjectCenter = function () {
  68161. if (this.object.getBoundingInfo) {
  68162. var boundingInfo = this.object.getBoundingInfo();
  68163. return boundingInfo.boundingBox.centerWorld;
  68164. }
  68165. else {
  68166. return this.object.position;
  68167. }
  68168. };
  68169. /**
  68170. * Get a specific parametes from the options parameter.
  68171. */
  68172. PhysicsImpostor.prototype.getParam = function (paramName) {
  68173. return this._options[paramName];
  68174. };
  68175. /**
  68176. * Sets a specific parameter in the options given to the physics plugin
  68177. */
  68178. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68179. this._options[paramName] = value;
  68180. this._bodyUpdateRequired = true;
  68181. };
  68182. /**
  68183. * Specifically change the body's mass option. Won't recreate the physics body object
  68184. */
  68185. PhysicsImpostor.prototype.setMass = function (mass) {
  68186. if (this.getParam("mass") !== mass) {
  68187. this.setParam("mass", mass);
  68188. }
  68189. if (this._physicsEngine) {
  68190. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68191. }
  68192. };
  68193. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68194. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68195. };
  68196. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68197. if (this._physicsEngine) {
  68198. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68199. }
  68200. };
  68201. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68202. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68203. };
  68204. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68205. if (this._physicsEngine) {
  68206. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68207. }
  68208. };
  68209. /**
  68210. * Execute a function with the physics plugin native code.
  68211. * Provide a function the will have two variables - the world object and the physics body object.
  68212. */
  68213. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68214. if (this._physicsEngine) {
  68215. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68216. }
  68217. };
  68218. /**
  68219. * Register a function that will be executed before the physics world is stepping forward.
  68220. */
  68221. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68222. this._onBeforePhysicsStepCallbacks.push(func);
  68223. };
  68224. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68225. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68226. if (index > -1) {
  68227. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68228. }
  68229. else {
  68230. BABYLON.Tools.Warn("Function to remove was not found");
  68231. }
  68232. };
  68233. /**
  68234. * Register a function that will be executed after the physics step
  68235. */
  68236. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68237. this._onAfterPhysicsStepCallbacks.push(func);
  68238. };
  68239. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68240. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68241. if (index > -1) {
  68242. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68243. }
  68244. else {
  68245. BABYLON.Tools.Warn("Function to remove was not found");
  68246. }
  68247. };
  68248. /**
  68249. * register a function that will be executed when this impostor collides against a different body.
  68250. */
  68251. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68252. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68253. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68254. };
  68255. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68256. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68257. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68258. if (index > -1) {
  68259. this._onPhysicsCollideCallbacks.splice(index, 1);
  68260. }
  68261. else {
  68262. BABYLON.Tools.Warn("Function to remove was not found");
  68263. }
  68264. };
  68265. PhysicsImpostor.prototype.getParentsRotation = function () {
  68266. var parent = this.object.parent;
  68267. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68268. while (parent) {
  68269. if (parent.rotationQuaternion) {
  68270. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68271. }
  68272. else {
  68273. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68274. }
  68275. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68276. parent = parent.parent;
  68277. }
  68278. return this._tmpQuat;
  68279. };
  68280. /**
  68281. * Apply a force
  68282. */
  68283. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68284. if (this._physicsEngine) {
  68285. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68286. }
  68287. return this;
  68288. };
  68289. /**
  68290. * Apply an impulse
  68291. */
  68292. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68293. if (this._physicsEngine) {
  68294. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68295. }
  68296. return this;
  68297. };
  68298. /**
  68299. * A help function to create a joint.
  68300. */
  68301. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68302. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68303. this.addJoint(otherImpostor, joint);
  68304. return this;
  68305. };
  68306. /**
  68307. * Add a joint to this impostor with a different impostor.
  68308. */
  68309. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68310. this._joints.push({
  68311. otherImpostor: otherImpostor,
  68312. joint: joint
  68313. });
  68314. if (this._physicsEngine) {
  68315. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68316. }
  68317. return this;
  68318. };
  68319. /**
  68320. * Will keep this body still, in a sleep mode.
  68321. */
  68322. PhysicsImpostor.prototype.sleep = function () {
  68323. if (this._physicsEngine) {
  68324. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68325. }
  68326. return this;
  68327. };
  68328. /**
  68329. * Wake the body up.
  68330. */
  68331. PhysicsImpostor.prototype.wakeUp = function () {
  68332. if (this._physicsEngine) {
  68333. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68334. }
  68335. return this;
  68336. };
  68337. PhysicsImpostor.prototype.clone = function (newObject) {
  68338. if (!newObject)
  68339. return null;
  68340. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68341. };
  68342. PhysicsImpostor.prototype.dispose = function () {
  68343. var _this = this;
  68344. //no dispose if no physics engine is available.
  68345. if (!this._physicsEngine) {
  68346. return;
  68347. }
  68348. this._joints.forEach(function (j) {
  68349. if (_this._physicsEngine) {
  68350. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68351. }
  68352. });
  68353. //dispose the physics body
  68354. this._physicsEngine.removeImpostor(this);
  68355. if (this.parent) {
  68356. this.parent.forceUpdate();
  68357. }
  68358. else {
  68359. /*this._object.getChildMeshes().forEach(function(mesh) {
  68360. if (mesh.physicsImpostor) {
  68361. if (disposeChildren) {
  68362. mesh.physicsImpostor.dispose();
  68363. mesh.physicsImpostor = null;
  68364. }
  68365. }
  68366. })*/
  68367. }
  68368. this._isDisposed = true;
  68369. };
  68370. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68371. this._deltaPosition.copyFrom(position);
  68372. };
  68373. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68374. if (!this._deltaRotation) {
  68375. this._deltaRotation = new BABYLON.Quaternion();
  68376. }
  68377. this._deltaRotation.copyFrom(rotation);
  68378. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68379. };
  68380. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68381. if (this._physicsEngine) {
  68382. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68383. }
  68384. return this;
  68385. };
  68386. PhysicsImpostor.prototype.getRadius = function () {
  68387. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68388. };
  68389. /**
  68390. * Sync a bone with this impostor
  68391. * @param bone The bone to sync to the impostor.
  68392. * @param boneMesh The mesh that the bone is influencing.
  68393. * @param jointPivot The pivot of the joint / bone in local space.
  68394. * @param distToJoint Optional distance from the impostor to the joint.
  68395. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68396. */
  68397. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68398. var tempVec = PhysicsImpostor._tmpVecs[0];
  68399. var mesh = this.object;
  68400. if (mesh.rotationQuaternion) {
  68401. if (adjustRotation) {
  68402. var tempQuat = PhysicsImpostor._tmpQuat;
  68403. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68404. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68405. }
  68406. else {
  68407. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68408. }
  68409. }
  68410. tempVec.x = 0;
  68411. tempVec.y = 0;
  68412. tempVec.z = 0;
  68413. if (jointPivot) {
  68414. tempVec.x = jointPivot.x;
  68415. tempVec.y = jointPivot.y;
  68416. tempVec.z = jointPivot.z;
  68417. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68418. if (distToJoint === undefined || distToJoint === null) {
  68419. distToJoint = jointPivot.length();
  68420. }
  68421. tempVec.x *= distToJoint;
  68422. tempVec.y *= distToJoint;
  68423. tempVec.z *= distToJoint;
  68424. }
  68425. if (bone.getParent()) {
  68426. tempVec.addInPlace(mesh.getAbsolutePosition());
  68427. bone.setAbsolutePosition(tempVec, boneMesh);
  68428. }
  68429. else {
  68430. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68431. boneMesh.position.x -= tempVec.x;
  68432. boneMesh.position.y -= tempVec.y;
  68433. boneMesh.position.z -= tempVec.z;
  68434. }
  68435. };
  68436. /**
  68437. * Sync impostor to a bone
  68438. * @param bone The bone that the impostor will be synced to.
  68439. * @param boneMesh The mesh that the bone is influencing.
  68440. * @param jointPivot The pivot of the joint / bone in local space.
  68441. * @param distToJoint Optional distance from the impostor to the joint.
  68442. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68443. * @param boneAxis Optional vector3 axis the bone is aligned with
  68444. */
  68445. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68446. var mesh = this.object;
  68447. if (mesh.rotationQuaternion) {
  68448. if (adjustRotation) {
  68449. var tempQuat = PhysicsImpostor._tmpQuat;
  68450. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68451. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68452. }
  68453. else {
  68454. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68455. }
  68456. }
  68457. var pos = PhysicsImpostor._tmpVecs[0];
  68458. var boneDir = PhysicsImpostor._tmpVecs[1];
  68459. if (!boneAxis) {
  68460. boneAxis = PhysicsImpostor._tmpVecs[2];
  68461. boneAxis.x = 0;
  68462. boneAxis.y = 1;
  68463. boneAxis.z = 0;
  68464. }
  68465. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68466. bone.getAbsolutePositionToRef(boneMesh, pos);
  68467. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68468. distToJoint = jointPivot.length();
  68469. }
  68470. if (distToJoint !== undefined && distToJoint !== null) {
  68471. pos.x += boneDir.x * distToJoint;
  68472. pos.y += boneDir.y * distToJoint;
  68473. pos.z += boneDir.z * distToJoint;
  68474. }
  68475. mesh.setAbsolutePosition(pos);
  68476. };
  68477. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68478. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68479. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68480. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68481. //Impostor types
  68482. PhysicsImpostor.NoImpostor = 0;
  68483. PhysicsImpostor.SphereImpostor = 1;
  68484. PhysicsImpostor.BoxImpostor = 2;
  68485. PhysicsImpostor.PlaneImpostor = 3;
  68486. PhysicsImpostor.MeshImpostor = 4;
  68487. PhysicsImpostor.CylinderImpostor = 7;
  68488. PhysicsImpostor.ParticleImpostor = 8;
  68489. PhysicsImpostor.HeightmapImpostor = 9;
  68490. return PhysicsImpostor;
  68491. }());
  68492. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68493. })(BABYLON || (BABYLON = {}));
  68494. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68495. var BABYLON;
  68496. (function (BABYLON) {
  68497. var PhysicsEngine = /** @class */ (function () {
  68498. function PhysicsEngine(gravity, _physicsPlugin) {
  68499. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68500. this._physicsPlugin = _physicsPlugin;
  68501. //new methods and parameters
  68502. this._impostors = [];
  68503. this._joints = [];
  68504. if (!this._physicsPlugin.isSupported()) {
  68505. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68506. + "Please make sure it is included.");
  68507. }
  68508. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68509. this.setGravity(gravity);
  68510. this.setTimeStep();
  68511. }
  68512. PhysicsEngine.prototype.setGravity = function (gravity) {
  68513. this.gravity = gravity;
  68514. this._physicsPlugin.setGravity(this.gravity);
  68515. };
  68516. /**
  68517. * Set the time step of the physics engine.
  68518. * default is 1/60.
  68519. * To slow it down, enter 1/600 for example.
  68520. * To speed it up, 1/30
  68521. * @param {number} newTimeStep the new timestep to apply to this world.
  68522. */
  68523. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68524. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68525. this._physicsPlugin.setTimeStep(newTimeStep);
  68526. };
  68527. /**
  68528. * Get the time step of the physics engine.
  68529. */
  68530. PhysicsEngine.prototype.getTimeStep = function () {
  68531. return this._physicsPlugin.getTimeStep();
  68532. };
  68533. PhysicsEngine.prototype.dispose = function () {
  68534. this._impostors.forEach(function (impostor) {
  68535. impostor.dispose();
  68536. });
  68537. this._physicsPlugin.dispose();
  68538. };
  68539. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68540. return this._physicsPlugin.name;
  68541. };
  68542. /**
  68543. * Adding a new impostor for the impostor tracking.
  68544. * This will be done by the impostor itself.
  68545. * @param {PhysicsImpostor} impostor the impostor to add
  68546. */
  68547. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68548. impostor.uniqueId = this._impostors.push(impostor);
  68549. //if no parent, generate the body
  68550. if (!impostor.parent) {
  68551. this._physicsPlugin.generatePhysicsBody(impostor);
  68552. }
  68553. };
  68554. /**
  68555. * Remove an impostor from the engine.
  68556. * This impostor and its mesh will not longer be updated by the physics engine.
  68557. * @param {PhysicsImpostor} impostor the impostor to remove
  68558. */
  68559. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68560. var index = this._impostors.indexOf(impostor);
  68561. if (index > -1) {
  68562. var removed = this._impostors.splice(index, 1);
  68563. //Is it needed?
  68564. if (removed.length) {
  68565. //this will also remove it from the world.
  68566. removed[0].physicsBody = null;
  68567. }
  68568. }
  68569. };
  68570. /**
  68571. * Add a joint to the physics engine
  68572. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68573. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68574. * @param {PhysicsJoint} the joint that will connect both impostors.
  68575. */
  68576. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68577. var impostorJoint = {
  68578. mainImpostor: mainImpostor,
  68579. connectedImpostor: connectedImpostor,
  68580. joint: joint
  68581. };
  68582. joint.physicsPlugin = this._physicsPlugin;
  68583. this._joints.push(impostorJoint);
  68584. this._physicsPlugin.generateJoint(impostorJoint);
  68585. };
  68586. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68587. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68588. return (impostorJoint.connectedImpostor === connectedImpostor
  68589. && impostorJoint.joint === joint
  68590. && impostorJoint.mainImpostor === mainImpostor);
  68591. });
  68592. if (matchingJoints.length) {
  68593. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68594. //TODO remove it from the list as well
  68595. }
  68596. };
  68597. /**
  68598. * Called by the scene. no need to call it.
  68599. */
  68600. PhysicsEngine.prototype._step = function (delta) {
  68601. var _this = this;
  68602. //check if any mesh has no body / requires an update
  68603. this._impostors.forEach(function (impostor) {
  68604. if (impostor.isBodyInitRequired()) {
  68605. _this._physicsPlugin.generatePhysicsBody(impostor);
  68606. }
  68607. });
  68608. if (delta > 0.1) {
  68609. delta = 0.1;
  68610. }
  68611. else if (delta <= 0) {
  68612. delta = 1.0 / 60.0;
  68613. }
  68614. this._physicsPlugin.executeStep(delta, this._impostors);
  68615. };
  68616. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68617. return this._physicsPlugin;
  68618. };
  68619. PhysicsEngine.prototype.getImpostors = function () {
  68620. return this._impostors;
  68621. };
  68622. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68623. for (var i = 0; i < this._impostors.length; ++i) {
  68624. if (this._impostors[i].object === object) {
  68625. return this._impostors[i];
  68626. }
  68627. }
  68628. return null;
  68629. };
  68630. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68631. for (var i = 0; i < this._impostors.length; ++i) {
  68632. if (this._impostors[i].physicsBody === body) {
  68633. return this._impostors[i];
  68634. }
  68635. }
  68636. return null;
  68637. };
  68638. // Statics
  68639. PhysicsEngine.Epsilon = 0.001;
  68640. return PhysicsEngine;
  68641. }());
  68642. BABYLON.PhysicsEngine = PhysicsEngine;
  68643. })(BABYLON || (BABYLON = {}));
  68644. //# sourceMappingURL=babylon.physicsEngine.js.map
  68645. var BABYLON;
  68646. (function (BABYLON) {
  68647. var PhysicsHelper = /** @class */ (function () {
  68648. function PhysicsHelper(scene) {
  68649. this._scene = scene;
  68650. this._physicsEngine = this._scene.getPhysicsEngine();
  68651. if (!this._physicsEngine) {
  68652. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68653. }
  68654. }
  68655. /**
  68656. * @param {Vector3} origin the origin of the explosion
  68657. * @param {number} radius the explosion radius
  68658. * @param {number} strength the explosion strength
  68659. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68660. */
  68661. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68662. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68663. if (!this._physicsEngine) {
  68664. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68665. return null;
  68666. }
  68667. var impostors = this._physicsEngine.getImpostors();
  68668. if (impostors.length === 0) {
  68669. return null;
  68670. }
  68671. var event = new PhysicsRadialExplosionEvent(this._scene);
  68672. impostors.forEach(function (impostor) {
  68673. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68674. if (!impostorForceAndContactPoint) {
  68675. return;
  68676. }
  68677. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68678. });
  68679. event.dispose(false);
  68680. return event;
  68681. };
  68682. /**
  68683. * @param {Vector3} origin the origin of the explosion
  68684. * @param {number} radius the explosion radius
  68685. * @param {number} strength the explosion strength
  68686. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68687. */
  68688. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68689. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68690. if (!this._physicsEngine) {
  68691. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68692. return null;
  68693. }
  68694. var impostors = this._physicsEngine.getImpostors();
  68695. if (impostors.length === 0) {
  68696. return null;
  68697. }
  68698. var event = new PhysicsRadialExplosionEvent(this._scene);
  68699. impostors.forEach(function (impostor) {
  68700. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68701. if (!impostorForceAndContactPoint) {
  68702. return;
  68703. }
  68704. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68705. });
  68706. event.dispose(false);
  68707. return event;
  68708. };
  68709. /**
  68710. * @param {Vector3} origin the origin of the explosion
  68711. * @param {number} radius the explosion radius
  68712. * @param {number} strength the explosion strength
  68713. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68714. */
  68715. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68716. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68717. if (!this._physicsEngine) {
  68718. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68719. return null;
  68720. }
  68721. var impostors = this._physicsEngine.getImpostors();
  68722. if (impostors.length === 0) {
  68723. return null;
  68724. }
  68725. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68726. event.dispose(false);
  68727. return event;
  68728. };
  68729. /**
  68730. * @param {Vector3} origin the origin of the updraft
  68731. * @param {number} radius the radius of the updraft
  68732. * @param {number} strength the strength of the updraft
  68733. * @param {number} height the height of the updraft
  68734. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68735. */
  68736. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68737. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68738. if (!this._physicsEngine) {
  68739. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68740. return null;
  68741. }
  68742. if (this._physicsEngine.getImpostors().length === 0) {
  68743. return null;
  68744. }
  68745. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68746. event.dispose(false);
  68747. return event;
  68748. };
  68749. /**
  68750. * @param {Vector3} origin the of the vortex
  68751. * @param {number} radius the radius of the vortex
  68752. * @param {number} strength the strength of the vortex
  68753. * @param {number} height the height of the vortex
  68754. */
  68755. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68756. if (!this._physicsEngine) {
  68757. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68758. return null;
  68759. }
  68760. if (this._physicsEngine.getImpostors().length === 0) {
  68761. return null;
  68762. }
  68763. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68764. event.dispose(false);
  68765. return event;
  68766. };
  68767. return PhysicsHelper;
  68768. }());
  68769. BABYLON.PhysicsHelper = PhysicsHelper;
  68770. /***** Radial explosion *****/
  68771. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68772. function PhysicsRadialExplosionEvent(scene) {
  68773. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68774. this._rays = [];
  68775. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68776. this._scene = scene;
  68777. }
  68778. /**
  68779. * Returns the data related to the radial explosion event (sphere & rays).
  68780. * @returns {PhysicsRadialExplosionEventData}
  68781. */
  68782. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68783. this._dataFetched = true;
  68784. return {
  68785. sphere: this._sphere,
  68786. rays: this._rays,
  68787. };
  68788. };
  68789. /**
  68790. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68791. * @param impostor
  68792. * @param {Vector3} origin the origin of the explosion
  68793. * @param {number} radius the explosion radius
  68794. * @param {number} strength the explosion strength
  68795. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68796. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68797. */
  68798. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68799. if (impostor.mass === 0) {
  68800. return null;
  68801. }
  68802. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68803. return null;
  68804. }
  68805. if (impostor.object.getClassName() !== 'Mesh') {
  68806. return null;
  68807. }
  68808. var impostorObject = impostor.object;
  68809. var impostorObjectCenter = impostor.getObjectCenter();
  68810. var direction = impostorObjectCenter.subtract(origin);
  68811. var ray = new BABYLON.Ray(origin, direction, radius);
  68812. this._rays.push(ray);
  68813. var hit = ray.intersectsMesh(impostorObject);
  68814. var contactPoint = hit.pickedPoint;
  68815. if (!contactPoint) {
  68816. return null;
  68817. }
  68818. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68819. if (distanceFromOrigin > radius) {
  68820. return null;
  68821. }
  68822. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68823. ? strength
  68824. : strength * (1 - (distanceFromOrigin / radius));
  68825. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68826. return { force: force, contactPoint: contactPoint };
  68827. };
  68828. /**
  68829. * Disposes the sphere.
  68830. * @param {bolean} force
  68831. */
  68832. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68833. var _this = this;
  68834. if (force === void 0) { force = true; }
  68835. if (force) {
  68836. this._sphere.dispose();
  68837. }
  68838. else {
  68839. setTimeout(function () {
  68840. if (!_this._dataFetched) {
  68841. _this._sphere.dispose();
  68842. }
  68843. }, 0);
  68844. }
  68845. };
  68846. /*** Helpers ***/
  68847. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68848. if (!this._sphere) {
  68849. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68850. this._sphere.isVisible = false;
  68851. }
  68852. };
  68853. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68854. var impostorObject = impostor.object;
  68855. this._prepareSphere();
  68856. this._sphere.position = origin;
  68857. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68858. this._sphere._updateBoundingInfo();
  68859. this._sphere.computeWorldMatrix(true);
  68860. return this._sphere.intersectsMesh(impostorObject, true);
  68861. };
  68862. return PhysicsRadialExplosionEvent;
  68863. }());
  68864. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68865. /***** Gravitational Field *****/
  68866. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68867. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68868. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68869. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68870. this._physicsHelper = physicsHelper;
  68871. this._scene = scene;
  68872. this._origin = origin;
  68873. this._radius = radius;
  68874. this._strength = strength;
  68875. this._falloff = falloff;
  68876. this._tickCallback = this._tick.bind(this);
  68877. }
  68878. /**
  68879. * Returns the data related to the gravitational field event (sphere).
  68880. * @returns {PhysicsGravitationalFieldEventData}
  68881. */
  68882. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68883. this._dataFetched = true;
  68884. return {
  68885. sphere: this._sphere,
  68886. };
  68887. };
  68888. /**
  68889. * Enables the gravitational field.
  68890. */
  68891. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68892. this._tickCallback.call(this);
  68893. this._scene.registerBeforeRender(this._tickCallback);
  68894. };
  68895. /**
  68896. * Disables the gravitational field.
  68897. */
  68898. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68899. this._scene.unregisterBeforeRender(this._tickCallback);
  68900. };
  68901. /**
  68902. * Disposes the sphere.
  68903. * @param {bolean} force
  68904. */
  68905. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68906. var _this = this;
  68907. if (force === void 0) { force = true; }
  68908. if (force) {
  68909. this._sphere.dispose();
  68910. }
  68911. else {
  68912. setTimeout(function () {
  68913. if (!_this._dataFetched) {
  68914. _this._sphere.dispose();
  68915. }
  68916. }, 0);
  68917. }
  68918. };
  68919. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68920. // Since the params won't change, we fetch the event only once
  68921. if (this._sphere) {
  68922. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68923. }
  68924. else {
  68925. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68926. if (radialExplosionEvent) {
  68927. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68928. }
  68929. }
  68930. };
  68931. return PhysicsGravitationalFieldEvent;
  68932. }());
  68933. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68934. /***** Updraft *****/
  68935. var PhysicsUpdraftEvent = /** @class */ (function () {
  68936. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68937. this._scene = _scene;
  68938. this._origin = _origin;
  68939. this._radius = _radius;
  68940. this._strength = _strength;
  68941. this._height = _height;
  68942. this._updraftMode = _updraftMode;
  68943. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68944. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68945. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68946. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68947. this._physicsEngine = this._scene.getPhysicsEngine();
  68948. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68949. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68950. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68951. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68952. }
  68953. this._tickCallback = this._tick.bind(this);
  68954. }
  68955. /**
  68956. * Returns the data related to the updraft event (cylinder).
  68957. * @returns {PhysicsUpdraftEventData}
  68958. */
  68959. PhysicsUpdraftEvent.prototype.getData = function () {
  68960. this._dataFetched = true;
  68961. return {
  68962. cylinder: this._cylinder,
  68963. };
  68964. };
  68965. /**
  68966. * Enables the updraft.
  68967. */
  68968. PhysicsUpdraftEvent.prototype.enable = function () {
  68969. this._tickCallback.call(this);
  68970. this._scene.registerBeforeRender(this._tickCallback);
  68971. };
  68972. /**
  68973. * Disables the cortex.
  68974. */
  68975. PhysicsUpdraftEvent.prototype.disable = function () {
  68976. this._scene.unregisterBeforeRender(this._tickCallback);
  68977. };
  68978. /**
  68979. * Disposes the sphere.
  68980. * @param {bolean} force
  68981. */
  68982. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  68983. var _this = this;
  68984. if (force === void 0) { force = true; }
  68985. if (force) {
  68986. this._cylinder.dispose();
  68987. }
  68988. else {
  68989. setTimeout(function () {
  68990. if (!_this._dataFetched) {
  68991. _this._cylinder.dispose();
  68992. }
  68993. }, 0);
  68994. }
  68995. };
  68996. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68997. if (impostor.mass === 0) {
  68998. return null;
  68999. }
  69000. if (!this._intersectsWithCylinder(impostor)) {
  69001. return null;
  69002. }
  69003. var impostorObjectCenter = impostor.getObjectCenter();
  69004. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69005. var direction = this._originDirection;
  69006. }
  69007. else {
  69008. var direction = impostorObjectCenter.subtract(this._originTop);
  69009. }
  69010. var multiplier = this._strength * -1;
  69011. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69012. return { force: force, contactPoint: impostorObjectCenter };
  69013. };
  69014. PhysicsUpdraftEvent.prototype._tick = function () {
  69015. var _this = this;
  69016. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69017. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69018. if (!impostorForceAndContactPoint) {
  69019. return;
  69020. }
  69021. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69022. });
  69023. };
  69024. /*** Helpers ***/
  69025. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69026. if (!this._cylinder) {
  69027. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69028. height: this._height,
  69029. diameter: this._radius * 2,
  69030. }, this._scene);
  69031. this._cylinder.isVisible = false;
  69032. }
  69033. };
  69034. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69035. var impostorObject = impostor.object;
  69036. this._prepareCylinder();
  69037. this._cylinder.position = this._cylinderPosition;
  69038. return this._cylinder.intersectsMesh(impostorObject, true);
  69039. };
  69040. return PhysicsUpdraftEvent;
  69041. }());
  69042. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69043. /***** Vortex *****/
  69044. var PhysicsVortexEvent = /** @class */ (function () {
  69045. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69046. this._scene = _scene;
  69047. this._origin = _origin;
  69048. this._radius = _radius;
  69049. this._strength = _strength;
  69050. this._height = _height;
  69051. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69052. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69053. this._updraftMultiplier = 0.02;
  69054. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69055. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69056. this._physicsEngine = this._scene.getPhysicsEngine();
  69057. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69058. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69059. this._tickCallback = this._tick.bind(this);
  69060. }
  69061. /**
  69062. * Returns the data related to the vortex event (cylinder).
  69063. * @returns {PhysicsVortexEventData}
  69064. */
  69065. PhysicsVortexEvent.prototype.getData = function () {
  69066. this._dataFetched = true;
  69067. return {
  69068. cylinder: this._cylinder,
  69069. };
  69070. };
  69071. /**
  69072. * Enables the vortex.
  69073. */
  69074. PhysicsVortexEvent.prototype.enable = function () {
  69075. this._tickCallback.call(this);
  69076. this._scene.registerBeforeRender(this._tickCallback);
  69077. };
  69078. /**
  69079. * Disables the cortex.
  69080. */
  69081. PhysicsVortexEvent.prototype.disable = function () {
  69082. this._scene.unregisterBeforeRender(this._tickCallback);
  69083. };
  69084. /**
  69085. * Disposes the sphere.
  69086. * @param {bolean} force
  69087. */
  69088. PhysicsVortexEvent.prototype.dispose = function (force) {
  69089. var _this = this;
  69090. if (force === void 0) { force = true; }
  69091. if (force) {
  69092. this._cylinder.dispose();
  69093. }
  69094. else {
  69095. setTimeout(function () {
  69096. if (!_this._dataFetched) {
  69097. _this._cylinder.dispose();
  69098. }
  69099. }, 0);
  69100. }
  69101. };
  69102. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69103. if (impostor.mass === 0) {
  69104. return null;
  69105. }
  69106. if (!this._intersectsWithCylinder(impostor)) {
  69107. return null;
  69108. }
  69109. if (impostor.object.getClassName() !== 'Mesh') {
  69110. return null;
  69111. }
  69112. var impostorObject = impostor.object;
  69113. var impostorObjectCenter = impostor.getObjectCenter();
  69114. 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)
  69115. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69116. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69117. var hit = ray.intersectsMesh(impostorObject);
  69118. var contactPoint = hit.pickedPoint;
  69119. if (!contactPoint) {
  69120. return null;
  69121. }
  69122. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69123. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69124. var directionToOrigin = contactPoint.normalize();
  69125. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69126. directionToOrigin = directionToOrigin.negate();
  69127. }
  69128. // TODO: find a more physically based solution
  69129. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69130. var forceX = directionToOrigin.x * this._strength / 8;
  69131. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69132. var forceZ = directionToOrigin.z * this._strength / 8;
  69133. }
  69134. else {
  69135. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69136. var forceY = this._originTop.y * this._updraftMultiplier;
  69137. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69138. }
  69139. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69140. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69141. return { force: force, contactPoint: impostorObjectCenter };
  69142. };
  69143. PhysicsVortexEvent.prototype._tick = function () {
  69144. var _this = this;
  69145. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69146. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69147. if (!impostorForceAndContactPoint) {
  69148. return;
  69149. }
  69150. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69151. });
  69152. };
  69153. /*** Helpers ***/
  69154. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69155. if (!this._cylinder) {
  69156. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69157. height: this._height,
  69158. diameter: this._radius * 2,
  69159. }, this._scene);
  69160. this._cylinder.isVisible = false;
  69161. }
  69162. };
  69163. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69164. var impostorObject = impostor.object;
  69165. this._prepareCylinder();
  69166. this._cylinder.position = this._cylinderPosition;
  69167. return this._cylinder.intersectsMesh(impostorObject, true);
  69168. };
  69169. return PhysicsVortexEvent;
  69170. }());
  69171. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69172. /***** Enums *****/
  69173. /**
  69174. * The strenght of the force in correspondence to the distance of the affected object
  69175. */
  69176. var PhysicsRadialImpulseFalloff;
  69177. (function (PhysicsRadialImpulseFalloff) {
  69178. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69179. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69180. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69181. /**
  69182. * The strenght of the force in correspondence to the distance of the affected object
  69183. */
  69184. var PhysicsUpdraftMode;
  69185. (function (PhysicsUpdraftMode) {
  69186. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69187. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69188. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69189. })(BABYLON || (BABYLON = {}));
  69190. //# sourceMappingURL=babylon.physicsHelper.js.map
  69191. var BABYLON;
  69192. (function (BABYLON) {
  69193. var CannonJSPlugin = /** @class */ (function () {
  69194. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69195. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69196. if (iterations === void 0) { iterations = 10; }
  69197. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69198. this.name = "CannonJSPlugin";
  69199. this._physicsMaterials = new Array();
  69200. this._fixedTimeStep = 1 / 60;
  69201. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69202. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69203. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69204. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69205. this._tmpPosition = BABYLON.Vector3.Zero();
  69206. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69207. this._tmpUnityRotation = new BABYLON.Quaternion();
  69208. if (!this.isSupported()) {
  69209. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69210. return;
  69211. }
  69212. this._extendNamespace();
  69213. this.world = new this.BJSCANNON.World();
  69214. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69215. this.world.solver.iterations = iterations;
  69216. }
  69217. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69218. this.world.gravity.copy(gravity);
  69219. };
  69220. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69221. this._fixedTimeStep = timeStep;
  69222. };
  69223. CannonJSPlugin.prototype.getTimeStep = function () {
  69224. return this._fixedTimeStep;
  69225. };
  69226. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69227. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69228. };
  69229. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69230. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69231. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69232. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69233. };
  69234. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69235. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69236. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69237. impostor.physicsBody.applyForce(impulse, worldPoint);
  69238. };
  69239. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69240. //parent-child relationship. Does this impostor has a parent impostor?
  69241. if (impostor.parent) {
  69242. if (impostor.physicsBody) {
  69243. this.removePhysicsBody(impostor);
  69244. //TODO is that needed?
  69245. impostor.forceUpdate();
  69246. }
  69247. return;
  69248. }
  69249. //should a new body be created for this impostor?
  69250. if (impostor.isBodyInitRequired()) {
  69251. var shape = this._createShape(impostor);
  69252. //unregister events, if body is being changed
  69253. var oldBody = impostor.physicsBody;
  69254. if (oldBody) {
  69255. this.removePhysicsBody(impostor);
  69256. }
  69257. //create the body and material
  69258. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69259. var bodyCreationObject = {
  69260. mass: impostor.getParam("mass"),
  69261. material: material
  69262. };
  69263. // A simple extend, in case native options were used.
  69264. var nativeOptions = impostor.getParam("nativeOptions");
  69265. for (var key in nativeOptions) {
  69266. if (nativeOptions.hasOwnProperty(key)) {
  69267. bodyCreationObject[key] = nativeOptions[key];
  69268. }
  69269. }
  69270. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69271. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69272. this.world.addEventListener("preStep", impostor.beforeStep);
  69273. this.world.addEventListener("postStep", impostor.afterStep);
  69274. impostor.physicsBody.addShape(shape);
  69275. this.world.add(impostor.physicsBody);
  69276. //try to keep the body moving in the right direction by taking old properties.
  69277. //Should be tested!
  69278. if (oldBody) {
  69279. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69280. impostor.physicsBody[param].copy(oldBody[param]);
  69281. });
  69282. }
  69283. this._processChildMeshes(impostor);
  69284. }
  69285. //now update the body's transformation
  69286. this._updatePhysicsBodyTransformation(impostor);
  69287. };
  69288. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69289. var _this = this;
  69290. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69291. var currentRotation = mainImpostor.object.rotationQuaternion;
  69292. if (meshChildren.length) {
  69293. var processMesh = function (localPosition, mesh) {
  69294. if (!currentRotation || !mesh.rotationQuaternion) {
  69295. return;
  69296. }
  69297. var childImpostor = mesh.getPhysicsImpostor();
  69298. if (childImpostor) {
  69299. var parent = childImpostor.parent;
  69300. if (parent !== mainImpostor) {
  69301. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69302. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69303. if (childImpostor.physicsBody) {
  69304. _this.removePhysicsBody(childImpostor);
  69305. childImpostor.physicsBody = null;
  69306. }
  69307. childImpostor.parent = mainImpostor;
  69308. childImpostor.resetUpdateFlags();
  69309. 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));
  69310. //Add the mass of the children.
  69311. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69312. }
  69313. }
  69314. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69315. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69316. };
  69317. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69318. }
  69319. };
  69320. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69321. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69322. this.world.removeEventListener("preStep", impostor.beforeStep);
  69323. this.world.removeEventListener("postStep", impostor.afterStep);
  69324. this.world.remove(impostor.physicsBody);
  69325. };
  69326. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69327. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69328. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69329. if (!mainBody || !connectedBody) {
  69330. return;
  69331. }
  69332. var constraint;
  69333. var jointData = impostorJoint.joint.jointData;
  69334. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69335. var constraintData = {
  69336. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69337. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69338. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69339. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69340. maxForce: jointData.nativeParams.maxForce,
  69341. collideConnected: !!jointData.collision
  69342. };
  69343. switch (impostorJoint.joint.type) {
  69344. case BABYLON.PhysicsJoint.HingeJoint:
  69345. case BABYLON.PhysicsJoint.Hinge2Joint:
  69346. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69347. break;
  69348. case BABYLON.PhysicsJoint.DistanceJoint:
  69349. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69350. break;
  69351. case BABYLON.PhysicsJoint.SpringJoint:
  69352. var springData = jointData;
  69353. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69354. restLength: springData.length,
  69355. stiffness: springData.stiffness,
  69356. damping: springData.damping,
  69357. localAnchorA: constraintData.pivotA,
  69358. localAnchorB: constraintData.pivotB
  69359. });
  69360. break;
  69361. case BABYLON.PhysicsJoint.LockJoint:
  69362. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69363. break;
  69364. case BABYLON.PhysicsJoint.PointToPointJoint:
  69365. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69366. default:
  69367. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69368. break;
  69369. }
  69370. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69371. constraint.collideConnected = !!jointData.collision;
  69372. impostorJoint.joint.physicsJoint = constraint;
  69373. //don't add spring as constraint, as it is not one.
  69374. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69375. this.world.addConstraint(constraint);
  69376. }
  69377. else {
  69378. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69379. constraint.applyForce();
  69380. });
  69381. }
  69382. };
  69383. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69384. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69385. };
  69386. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69387. var index;
  69388. var mat;
  69389. for (index = 0; index < this._physicsMaterials.length; index++) {
  69390. mat = this._physicsMaterials[index];
  69391. if (mat.friction === friction && mat.restitution === restitution) {
  69392. return mat;
  69393. }
  69394. }
  69395. var currentMat = new this.BJSCANNON.Material(name);
  69396. currentMat.friction = friction;
  69397. currentMat.restitution = restitution;
  69398. this._physicsMaterials.push(currentMat);
  69399. return currentMat;
  69400. };
  69401. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69402. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69403. };
  69404. CannonJSPlugin.prototype._createShape = function (impostor) {
  69405. var object = impostor.object;
  69406. var returnValue;
  69407. var extendSize = impostor.getObjectExtendSize();
  69408. switch (impostor.type) {
  69409. case BABYLON.PhysicsImpostor.SphereImpostor:
  69410. var radiusX = extendSize.x;
  69411. var radiusY = extendSize.y;
  69412. var radiusZ = extendSize.z;
  69413. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69414. break;
  69415. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69416. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69417. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69418. break;
  69419. case BABYLON.PhysicsImpostor.BoxImpostor:
  69420. var box = extendSize.scale(0.5);
  69421. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69422. break;
  69423. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69424. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69425. returnValue = new this.BJSCANNON.Plane();
  69426. break;
  69427. case BABYLON.PhysicsImpostor.MeshImpostor:
  69428. // should transform the vertex data to world coordinates!!
  69429. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69430. var rawFaces = object.getIndices ? object.getIndices() : [];
  69431. if (!rawVerts)
  69432. return;
  69433. // get only scale! so the object could transform correctly.
  69434. var oldPosition = object.position.clone();
  69435. var oldRotation = object.rotation && object.rotation.clone();
  69436. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69437. object.position.copyFromFloats(0, 0, 0);
  69438. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69439. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69440. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69441. var transform = object.computeWorldMatrix(true);
  69442. // convert rawVerts to object space
  69443. var temp = new Array();
  69444. var index;
  69445. for (index = 0; index < rawVerts.length; index += 3) {
  69446. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69447. }
  69448. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69449. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69450. //now set back the transformation!
  69451. object.position.copyFrom(oldPosition);
  69452. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69453. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69454. break;
  69455. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69456. var oldPosition2 = object.position.clone();
  69457. var oldRotation2 = object.rotation && object.rotation.clone();
  69458. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69459. object.position.copyFromFloats(0, 0, 0);
  69460. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69461. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69462. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69463. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69464. returnValue = this._createHeightmap(object);
  69465. object.position.copyFrom(oldPosition2);
  69466. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69467. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69468. object.computeWorldMatrix(true);
  69469. break;
  69470. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69471. returnValue = new this.BJSCANNON.Particle();
  69472. break;
  69473. }
  69474. return returnValue;
  69475. };
  69476. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69477. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69478. var transform = object.computeWorldMatrix(true);
  69479. // convert rawVerts to object space
  69480. var temp = new Array();
  69481. var index;
  69482. for (index = 0; index < pos.length; index += 3) {
  69483. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69484. }
  69485. pos = temp;
  69486. var matrix = new Array();
  69487. //For now pointDepth will not be used and will be automatically calculated.
  69488. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69489. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69490. var boundingInfo = object.getBoundingInfo();
  69491. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69492. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69493. var elementSize = dim * 2 / arraySize;
  69494. for (var i = 0; i < pos.length; i = i + 3) {
  69495. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69496. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69497. var y = -pos[i + 2] + minY;
  69498. if (!matrix[x]) {
  69499. matrix[x] = [];
  69500. }
  69501. if (!matrix[x][z]) {
  69502. matrix[x][z] = y;
  69503. }
  69504. matrix[x][z] = Math.max(y, matrix[x][z]);
  69505. }
  69506. for (var x = 0; x <= arraySize; ++x) {
  69507. if (!matrix[x]) {
  69508. var loc = 1;
  69509. while (!matrix[(x + loc) % arraySize]) {
  69510. loc++;
  69511. }
  69512. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69513. //console.log("missing x", x);
  69514. }
  69515. for (var z = 0; z <= arraySize; ++z) {
  69516. if (!matrix[x][z]) {
  69517. var loc = 1;
  69518. var newValue;
  69519. while (newValue === undefined) {
  69520. newValue = matrix[x][(z + loc++) % arraySize];
  69521. }
  69522. matrix[x][z] = newValue;
  69523. }
  69524. }
  69525. }
  69526. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69527. elementSize: elementSize
  69528. });
  69529. //For future reference, needed for body transformation
  69530. shape.minY = minY;
  69531. return shape;
  69532. };
  69533. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69534. var object = impostor.object;
  69535. //make sure it is updated...
  69536. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69537. // The delta between the mesh position and the mesh bounding box center
  69538. var bInfo = object.getBoundingInfo();
  69539. if (!bInfo)
  69540. return;
  69541. var center = impostor.getObjectCenter();
  69542. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69543. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69544. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69545. this._tmpPosition.copyFrom(center);
  69546. var quaternion = object.rotationQuaternion;
  69547. if (!quaternion) {
  69548. return;
  69549. }
  69550. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69551. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69552. //-90 DEG in X, precalculated
  69553. quaternion = quaternion.multiply(this._minus90X);
  69554. //Invert! (Precalculated, 90 deg in X)
  69555. //No need to clone. this will never change.
  69556. impostor.setDeltaRotation(this._plus90X);
  69557. }
  69558. //If it is a heightfield, if should be centered.
  69559. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69560. var mesh = object;
  69561. var boundingInfo = mesh.getBoundingInfo();
  69562. //calculate the correct body position:
  69563. var rotationQuaternion = mesh.rotationQuaternion;
  69564. mesh.rotationQuaternion = this._tmpUnityRotation;
  69565. mesh.computeWorldMatrix(true);
  69566. //get original center with no rotation
  69567. var c = center.clone();
  69568. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69569. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69570. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69571. mesh.setPivotMatrix(p);
  69572. mesh.computeWorldMatrix(true);
  69573. //calculate the translation
  69574. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69575. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69576. //add it inverted to the delta
  69577. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69578. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69579. //rotation is back
  69580. mesh.rotationQuaternion = rotationQuaternion;
  69581. mesh.setPivotMatrix(oldPivot);
  69582. mesh.computeWorldMatrix(true);
  69583. }
  69584. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69585. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69586. //this._tmpPosition.copyFrom(object.position);
  69587. }
  69588. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69589. //Now update the impostor object
  69590. impostor.physicsBody.position.copy(this._tmpPosition);
  69591. impostor.physicsBody.quaternion.copy(quaternion);
  69592. };
  69593. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69594. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69595. if (impostor.object.rotationQuaternion) {
  69596. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69597. }
  69598. };
  69599. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69600. impostor.physicsBody.position.copy(newPosition);
  69601. impostor.physicsBody.quaternion.copy(newRotation);
  69602. };
  69603. CannonJSPlugin.prototype.isSupported = function () {
  69604. return this.BJSCANNON !== undefined;
  69605. };
  69606. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69607. impostor.physicsBody.velocity.copy(velocity);
  69608. };
  69609. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69610. impostor.physicsBody.angularVelocity.copy(velocity);
  69611. };
  69612. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69613. var v = impostor.physicsBody.velocity;
  69614. if (!v) {
  69615. return null;
  69616. }
  69617. return new BABYLON.Vector3(v.x, v.y, v.z);
  69618. };
  69619. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69620. var v = impostor.physicsBody.angularVelocity;
  69621. if (!v) {
  69622. return null;
  69623. }
  69624. return new BABYLON.Vector3(v.x, v.y, v.z);
  69625. };
  69626. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69627. impostor.physicsBody.mass = mass;
  69628. impostor.physicsBody.updateMassProperties();
  69629. };
  69630. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69631. return impostor.physicsBody.mass;
  69632. };
  69633. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69634. return impostor.physicsBody.material.friction;
  69635. };
  69636. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69637. impostor.physicsBody.material.friction = friction;
  69638. };
  69639. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69640. return impostor.physicsBody.material.restitution;
  69641. };
  69642. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69643. impostor.physicsBody.material.restitution = restitution;
  69644. };
  69645. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69646. impostor.physicsBody.sleep();
  69647. };
  69648. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69649. impostor.physicsBody.wakeUp();
  69650. };
  69651. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69652. joint.physicsJoint.distance = maxDistance;
  69653. };
  69654. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69655. // if (!motorIndex) {
  69656. // joint.physicsJoint.enableMotor();
  69657. // }
  69658. // }
  69659. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69660. // if (!motorIndex) {
  69661. // joint.physicsJoint.disableMotor();
  69662. // }
  69663. // }
  69664. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69665. if (!motorIndex) {
  69666. joint.physicsJoint.enableMotor();
  69667. joint.physicsJoint.setMotorSpeed(speed);
  69668. if (maxForce) {
  69669. this.setLimit(joint, maxForce);
  69670. }
  69671. }
  69672. };
  69673. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69674. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69675. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69676. };
  69677. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69678. var body = impostor.physicsBody;
  69679. mesh.position.x = body.position.x;
  69680. mesh.position.y = body.position.y;
  69681. mesh.position.z = body.position.z;
  69682. if (mesh.rotationQuaternion) {
  69683. mesh.rotationQuaternion.x = body.quaternion.x;
  69684. mesh.rotationQuaternion.y = body.quaternion.y;
  69685. mesh.rotationQuaternion.z = body.quaternion.z;
  69686. mesh.rotationQuaternion.w = body.quaternion.w;
  69687. }
  69688. };
  69689. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69690. var shape = impostor.physicsBody.shapes[0];
  69691. return shape.boundingSphereRadius;
  69692. };
  69693. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69694. var shape = impostor.physicsBody.shapes[0];
  69695. result.x = shape.halfExtents.x * 2;
  69696. result.y = shape.halfExtents.y * 2;
  69697. result.z = shape.halfExtents.z * 2;
  69698. };
  69699. CannonJSPlugin.prototype.dispose = function () {
  69700. };
  69701. CannonJSPlugin.prototype._extendNamespace = function () {
  69702. //this will force cannon to execute at least one step when using interpolation
  69703. var step_tmp1 = new this.BJSCANNON.Vec3();
  69704. var Engine = this.BJSCANNON;
  69705. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69706. maxSubSteps = maxSubSteps || 10;
  69707. timeSinceLastCalled = timeSinceLastCalled || 0;
  69708. if (timeSinceLastCalled === 0) {
  69709. this.internalStep(dt);
  69710. this.time += dt;
  69711. }
  69712. else {
  69713. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69714. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69715. var t0 = performance.now();
  69716. for (var i = 0; i !== internalSteps; i++) {
  69717. this.internalStep(dt);
  69718. if (performance.now() - t0 > dt * 1000) {
  69719. break;
  69720. }
  69721. }
  69722. this.time += timeSinceLastCalled;
  69723. var h = this.time % dt;
  69724. var h_div_dt = h / dt;
  69725. var interpvelo = step_tmp1;
  69726. var bodies = this.bodies;
  69727. for (var j = 0; j !== bodies.length; j++) {
  69728. var b = bodies[j];
  69729. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69730. b.position.vsub(b.previousPosition, interpvelo);
  69731. interpvelo.scale(h_div_dt, interpvelo);
  69732. b.position.vadd(interpvelo, b.interpolatedPosition);
  69733. }
  69734. else {
  69735. b.interpolatedPosition.copy(b.position);
  69736. b.interpolatedQuaternion.copy(b.quaternion);
  69737. }
  69738. }
  69739. }
  69740. };
  69741. };
  69742. return CannonJSPlugin;
  69743. }());
  69744. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69745. })(BABYLON || (BABYLON = {}));
  69746. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69747. var BABYLON;
  69748. (function (BABYLON) {
  69749. var OimoJSPlugin = /** @class */ (function () {
  69750. function OimoJSPlugin(iterations) {
  69751. this.name = "OimoJSPlugin";
  69752. this._tmpImpostorsArray = [];
  69753. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69754. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69755. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69756. this.world.worldscale(1);
  69757. this.world.clear();
  69758. //making sure no stats are calculated
  69759. this.world.isNoStat = true;
  69760. }
  69761. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69762. this.world.gravity.copy(gravity);
  69763. };
  69764. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69765. this.world.timeStep = timeStep;
  69766. };
  69767. OimoJSPlugin.prototype.getTimeStep = function () {
  69768. return this.world.timeStep;
  69769. };
  69770. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69771. var _this = this;
  69772. impostors.forEach(function (impostor) {
  69773. impostor.beforeStep();
  69774. });
  69775. this.world.step();
  69776. impostors.forEach(function (impostor) {
  69777. impostor.afterStep();
  69778. //update the ordered impostors array
  69779. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69780. });
  69781. //check for collisions
  69782. var contact = this.world.contacts;
  69783. while (contact !== null) {
  69784. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69785. contact = contact.next;
  69786. continue;
  69787. }
  69788. //is this body colliding with any other? get the impostor
  69789. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69790. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69791. if (!mainImpostor || !collidingImpostor) {
  69792. contact = contact.next;
  69793. continue;
  69794. }
  69795. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69796. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69797. contact = contact.next;
  69798. }
  69799. };
  69800. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69801. var mass = impostor.physicsBody.massInfo.mass;
  69802. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69803. };
  69804. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69805. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69806. this.applyImpulse(impostor, force, contactPoint);
  69807. };
  69808. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69809. var _this = this;
  69810. //parent-child relationship. Does this impostor has a parent impostor?
  69811. if (impostor.parent) {
  69812. if (impostor.physicsBody) {
  69813. this.removePhysicsBody(impostor);
  69814. //TODO is that needed?
  69815. impostor.forceUpdate();
  69816. }
  69817. return;
  69818. }
  69819. if (impostor.isBodyInitRequired()) {
  69820. var bodyConfig = {
  69821. name: impostor.uniqueId,
  69822. //Oimo must have mass, also for static objects.
  69823. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69824. size: [],
  69825. type: [],
  69826. pos: [],
  69827. rot: [],
  69828. move: impostor.getParam("mass") !== 0,
  69829. //Supporting older versions of Oimo
  69830. world: this.world
  69831. };
  69832. var impostors = [impostor];
  69833. var addToArray = function (parent) {
  69834. if (!parent.getChildMeshes)
  69835. return;
  69836. parent.getChildMeshes().forEach(function (m) {
  69837. if (m.physicsImpostor) {
  69838. impostors.push(m.physicsImpostor);
  69839. //m.physicsImpostor._init();
  69840. }
  69841. });
  69842. };
  69843. addToArray(impostor.object);
  69844. var checkWithEpsilon_1 = function (value) {
  69845. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69846. };
  69847. impostors.forEach(function (i) {
  69848. if (!impostor.object.rotationQuaternion) {
  69849. return;
  69850. }
  69851. //get the correct bounding box
  69852. var oldQuaternion = i.object.rotationQuaternion;
  69853. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69854. x: impostor.object.rotationQuaternion.x,
  69855. y: impostor.object.rotationQuaternion.y,
  69856. z: impostor.object.rotationQuaternion.z,
  69857. s: impostor.object.rotationQuaternion.w
  69858. });
  69859. var extendSize = i.getObjectExtendSize();
  69860. if (i === impostor) {
  69861. var center = impostor.getObjectCenter();
  69862. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  69863. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  69864. //Can also use Array.prototype.push.apply
  69865. bodyConfig.pos.push(center.x);
  69866. bodyConfig.pos.push(center.y);
  69867. bodyConfig.pos.push(center.z);
  69868. //tmp solution
  69869. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69870. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69871. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69872. }
  69873. else {
  69874. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69875. bodyConfig.pos.push(localPosition.x);
  69876. bodyConfig.pos.push(localPosition.y);
  69877. bodyConfig.pos.push(localPosition.z);
  69878. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69879. bodyConfig.rot.push(0);
  69880. bodyConfig.rot.push(0);
  69881. bodyConfig.rot.push(0);
  69882. }
  69883. // register mesh
  69884. switch (i.type) {
  69885. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69886. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69887. case BABYLON.PhysicsImpostor.SphereImpostor:
  69888. var radiusX = extendSize.x;
  69889. var radiusY = extendSize.y;
  69890. var radiusZ = extendSize.z;
  69891. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69892. bodyConfig.type.push('sphere');
  69893. //due to the way oimo works with compounds, add 3 times
  69894. bodyConfig.size.push(size);
  69895. bodyConfig.size.push(size);
  69896. bodyConfig.size.push(size);
  69897. break;
  69898. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69899. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69900. var sizeY = checkWithEpsilon_1(extendSize.y);
  69901. bodyConfig.type.push('cylinder');
  69902. bodyConfig.size.push(sizeX);
  69903. bodyConfig.size.push(sizeY);
  69904. //due to the way oimo works with compounds, add one more value.
  69905. bodyConfig.size.push(sizeY);
  69906. break;
  69907. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69908. case BABYLON.PhysicsImpostor.BoxImpostor:
  69909. default:
  69910. var sizeX = checkWithEpsilon_1(extendSize.x);
  69911. var sizeY = checkWithEpsilon_1(extendSize.y);
  69912. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69913. bodyConfig.type.push('box');
  69914. bodyConfig.size.push(sizeX);
  69915. bodyConfig.size.push(sizeY);
  69916. bodyConfig.size.push(sizeZ);
  69917. break;
  69918. }
  69919. //actually not needed, but hey...
  69920. i.object.rotationQuaternion = oldQuaternion;
  69921. });
  69922. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69923. }
  69924. else {
  69925. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69926. }
  69927. impostor.setDeltaPosition(this._tmpPositionVector);
  69928. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69929. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69930. };
  69931. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69932. //impostor.physicsBody.dispose();
  69933. //Same as : (older oimo versions)
  69934. this.world.removeRigidBody(impostor.physicsBody);
  69935. };
  69936. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69937. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69938. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69939. if (!mainBody || !connectedBody) {
  69940. return;
  69941. }
  69942. var jointData = impostorJoint.joint.jointData;
  69943. var options = jointData.nativeParams || {};
  69944. var type;
  69945. var nativeJointData = {
  69946. body1: mainBody,
  69947. body2: connectedBody,
  69948. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69949. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69950. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69951. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69952. min: options.min,
  69953. max: options.max,
  69954. collision: options.collision || jointData.collision,
  69955. spring: options.spring,
  69956. //supporting older version of Oimo
  69957. world: this.world
  69958. };
  69959. switch (impostorJoint.joint.type) {
  69960. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69961. type = "jointBall";
  69962. break;
  69963. case BABYLON.PhysicsJoint.SpringJoint:
  69964. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69965. var springData = jointData;
  69966. nativeJointData.min = springData.length || nativeJointData.min;
  69967. //Max should also be set, just make sure it is at least min
  69968. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  69969. case BABYLON.PhysicsJoint.DistanceJoint:
  69970. type = "jointDistance";
  69971. nativeJointData.max = jointData.maxDistance;
  69972. break;
  69973. case BABYLON.PhysicsJoint.PrismaticJoint:
  69974. type = "jointPrisme";
  69975. break;
  69976. case BABYLON.PhysicsJoint.SliderJoint:
  69977. type = "jointSlide";
  69978. break;
  69979. case BABYLON.PhysicsJoint.WheelJoint:
  69980. type = "jointWheel";
  69981. break;
  69982. case BABYLON.PhysicsJoint.HingeJoint:
  69983. default:
  69984. type = "jointHinge";
  69985. break;
  69986. }
  69987. nativeJointData.type = type;
  69988. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  69989. };
  69990. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69991. //Bug in Oimo prevents us from disposing a joint in the playground
  69992. //joint.joint.physicsJoint.dispose();
  69993. //So we will bruteforce it!
  69994. try {
  69995. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  69996. }
  69997. catch (e) {
  69998. BABYLON.Tools.Warn(e);
  69999. }
  70000. };
  70001. OimoJSPlugin.prototype.isSupported = function () {
  70002. return this.BJSOIMO !== undefined;
  70003. };
  70004. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70005. if (!impostor.physicsBody.sleeping) {
  70006. //TODO check that
  70007. if (impostor.physicsBody.shapes.next) {
  70008. var parentShape = this._getLastShape(impostor.physicsBody);
  70009. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70010. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70011. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70012. }
  70013. else {
  70014. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70015. }
  70016. if (impostor.object.rotationQuaternion) {
  70017. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70018. impostor.object.rotationQuaternion.normalize();
  70019. }
  70020. }
  70021. };
  70022. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70023. var body = impostor.physicsBody;
  70024. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70025. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70026. body.syncShapes();
  70027. body.awake();
  70028. };
  70029. OimoJSPlugin.prototype._getLastShape = function (body) {
  70030. var lastShape = body.shapes;
  70031. while (lastShape.next) {
  70032. lastShape = lastShape.next;
  70033. }
  70034. return lastShape;
  70035. };
  70036. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70037. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70038. };
  70039. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70040. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70041. };
  70042. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70043. var v = impostor.physicsBody.linearVelocity;
  70044. if (!v) {
  70045. return null;
  70046. }
  70047. return new BABYLON.Vector3(v.x, v.y, v.z);
  70048. };
  70049. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70050. var v = impostor.physicsBody.angularVelocity;
  70051. if (!v) {
  70052. return null;
  70053. }
  70054. return new BABYLON.Vector3(v.x, v.y, v.z);
  70055. };
  70056. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70057. var staticBody = mass === 0;
  70058. //this will actually set the body's density and not its mass.
  70059. //But this is how oimo treats the mass variable.
  70060. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70061. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70062. };
  70063. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70064. return impostor.physicsBody.shapes.density;
  70065. };
  70066. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70067. return impostor.physicsBody.shapes.friction;
  70068. };
  70069. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70070. impostor.physicsBody.shapes.friction = friction;
  70071. };
  70072. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70073. return impostor.physicsBody.shapes.restitution;
  70074. };
  70075. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70076. impostor.physicsBody.shapes.restitution = restitution;
  70077. };
  70078. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70079. impostor.physicsBody.sleep();
  70080. };
  70081. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70082. impostor.physicsBody.awake();
  70083. };
  70084. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70085. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70086. if (minDistance !== void 0) {
  70087. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70088. }
  70089. };
  70090. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70091. //TODO separate rotational and transational motors.
  70092. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70093. if (motor) {
  70094. motor.setMotor(speed, maxForce);
  70095. }
  70096. };
  70097. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70098. //TODO separate rotational and transational motors.
  70099. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70100. if (motor) {
  70101. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70102. }
  70103. };
  70104. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70105. var body = impostor.physicsBody;
  70106. mesh.position.x = body.position.x;
  70107. mesh.position.y = body.position.y;
  70108. mesh.position.z = body.position.z;
  70109. if (mesh.rotationQuaternion) {
  70110. mesh.rotationQuaternion.x = body.orientation.x;
  70111. mesh.rotationQuaternion.y = body.orientation.y;
  70112. mesh.rotationQuaternion.z = body.orientation.z;
  70113. mesh.rotationQuaternion.w = body.orientation.s;
  70114. }
  70115. };
  70116. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70117. return impostor.physicsBody.shapes.radius;
  70118. };
  70119. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70120. var shape = impostor.physicsBody.shapes;
  70121. result.x = shape.halfWidth * 2;
  70122. result.y = shape.halfHeight * 2;
  70123. result.z = shape.halfDepth * 2;
  70124. };
  70125. OimoJSPlugin.prototype.dispose = function () {
  70126. this.world.clear();
  70127. };
  70128. return OimoJSPlugin;
  70129. }());
  70130. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70131. })(BABYLON || (BABYLON = {}));
  70132. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70133. var BABYLON;
  70134. (function (BABYLON) {
  70135. /*
  70136. * Based on jsTGALoader - Javascript loader for TGA file
  70137. * By Vincent Thibault
  70138. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70139. */
  70140. var TGATools = /** @class */ (function () {
  70141. function TGATools() {
  70142. }
  70143. TGATools.GetTGAHeader = function (data) {
  70144. var offset = 0;
  70145. var header = {
  70146. id_length: data[offset++],
  70147. colormap_type: data[offset++],
  70148. image_type: data[offset++],
  70149. colormap_index: data[offset++] | data[offset++] << 8,
  70150. colormap_length: data[offset++] | data[offset++] << 8,
  70151. colormap_size: data[offset++],
  70152. origin: [
  70153. data[offset++] | data[offset++] << 8,
  70154. data[offset++] | data[offset++] << 8
  70155. ],
  70156. width: data[offset++] | data[offset++] << 8,
  70157. height: data[offset++] | data[offset++] << 8,
  70158. pixel_size: data[offset++],
  70159. flags: data[offset++]
  70160. };
  70161. return header;
  70162. };
  70163. TGATools.UploadContent = function (gl, data) {
  70164. // Not enough data to contain header ?
  70165. if (data.length < 19) {
  70166. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70167. return;
  70168. }
  70169. // Read Header
  70170. var offset = 18;
  70171. var header = TGATools.GetTGAHeader(data);
  70172. // Assume it's a valid Targa file.
  70173. if (header.id_length + offset > data.length) {
  70174. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70175. return;
  70176. }
  70177. // Skip not needed data
  70178. offset += header.id_length;
  70179. var use_rle = false;
  70180. var use_pal = false;
  70181. var use_grey = false;
  70182. // Get some informations.
  70183. switch (header.image_type) {
  70184. case TGATools._TYPE_RLE_INDEXED:
  70185. use_rle = true;
  70186. case TGATools._TYPE_INDEXED:
  70187. use_pal = true;
  70188. break;
  70189. case TGATools._TYPE_RLE_RGB:
  70190. use_rle = true;
  70191. case TGATools._TYPE_RGB:
  70192. // use_rgb = true;
  70193. break;
  70194. case TGATools._TYPE_RLE_GREY:
  70195. use_rle = true;
  70196. case TGATools._TYPE_GREY:
  70197. use_grey = true;
  70198. break;
  70199. }
  70200. var pixel_data;
  70201. // var numAlphaBits = header.flags & 0xf;
  70202. var pixel_size = header.pixel_size >> 3;
  70203. var pixel_total = header.width * header.height * pixel_size;
  70204. // Read palettes
  70205. var palettes;
  70206. if (use_pal) {
  70207. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70208. }
  70209. // Read LRE
  70210. if (use_rle) {
  70211. pixel_data = new Uint8Array(pixel_total);
  70212. var c, count, i;
  70213. var localOffset = 0;
  70214. var pixels = new Uint8Array(pixel_size);
  70215. while (offset < pixel_total && localOffset < pixel_total) {
  70216. c = data[offset++];
  70217. count = (c & 0x7f) + 1;
  70218. // RLE pixels
  70219. if (c & 0x80) {
  70220. // Bind pixel tmp array
  70221. for (i = 0; i < pixel_size; ++i) {
  70222. pixels[i] = data[offset++];
  70223. }
  70224. // Copy pixel array
  70225. for (i = 0; i < count; ++i) {
  70226. pixel_data.set(pixels, localOffset + i * pixel_size);
  70227. }
  70228. localOffset += pixel_size * count;
  70229. }
  70230. else {
  70231. count *= pixel_size;
  70232. for (i = 0; i < count; ++i) {
  70233. pixel_data[localOffset + i] = data[offset++];
  70234. }
  70235. localOffset += count;
  70236. }
  70237. }
  70238. }
  70239. else {
  70240. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70241. }
  70242. // Load to texture
  70243. var x_start, y_start, x_step, y_step, y_end, x_end;
  70244. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70245. default:
  70246. case TGATools._ORIGIN_UL:
  70247. x_start = 0;
  70248. x_step = 1;
  70249. x_end = header.width;
  70250. y_start = 0;
  70251. y_step = 1;
  70252. y_end = header.height;
  70253. break;
  70254. case TGATools._ORIGIN_BL:
  70255. x_start = 0;
  70256. x_step = 1;
  70257. x_end = header.width;
  70258. y_start = header.height - 1;
  70259. y_step = -1;
  70260. y_end = -1;
  70261. break;
  70262. case TGATools._ORIGIN_UR:
  70263. x_start = header.width - 1;
  70264. x_step = -1;
  70265. x_end = -1;
  70266. y_start = 0;
  70267. y_step = 1;
  70268. y_end = header.height;
  70269. break;
  70270. case TGATools._ORIGIN_BR:
  70271. x_start = header.width - 1;
  70272. x_step = -1;
  70273. x_end = -1;
  70274. y_start = header.height - 1;
  70275. y_step = -1;
  70276. y_end = -1;
  70277. break;
  70278. }
  70279. // Load the specify method
  70280. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70281. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70282. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70283. };
  70284. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70285. var image = pixel_data, colormap = palettes;
  70286. var width = header.width, height = header.height;
  70287. var color, i = 0, x, y;
  70288. var imageData = new Uint8Array(width * height * 4);
  70289. for (y = y_start; y !== y_end; y += y_step) {
  70290. for (x = x_start; x !== x_end; x += x_step, i++) {
  70291. color = image[i];
  70292. imageData[(x + width * y) * 4 + 3] = 255;
  70293. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70294. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70295. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70296. }
  70297. }
  70298. return imageData;
  70299. };
  70300. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70301. var image = pixel_data;
  70302. var width = header.width, height = header.height;
  70303. var color, i = 0, x, y;
  70304. var imageData = new Uint8Array(width * height * 4);
  70305. for (y = y_start; y !== y_end; y += y_step) {
  70306. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70307. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70308. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70309. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70310. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70311. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70312. }
  70313. }
  70314. return imageData;
  70315. };
  70316. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70317. var image = pixel_data;
  70318. var width = header.width, height = header.height;
  70319. var i = 0, x, y;
  70320. var imageData = new Uint8Array(width * height * 4);
  70321. for (y = y_start; y !== y_end; y += y_step) {
  70322. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70323. imageData[(x + width * y) * 4 + 3] = 255;
  70324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70327. }
  70328. }
  70329. return imageData;
  70330. };
  70331. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70332. var image = pixel_data;
  70333. var width = header.width, height = header.height;
  70334. var i = 0, x, y;
  70335. var imageData = new Uint8Array(width * height * 4);
  70336. for (y = y_start; y !== y_end; y += y_step) {
  70337. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70338. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70339. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70340. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70341. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70342. }
  70343. }
  70344. return imageData;
  70345. };
  70346. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70347. var image = pixel_data;
  70348. var width = header.width, height = header.height;
  70349. var color, i = 0, x, y;
  70350. var imageData = new Uint8Array(width * height * 4);
  70351. for (y = y_start; y !== y_end; y += y_step) {
  70352. for (x = x_start; x !== x_end; x += x_step, i++) {
  70353. color = image[i];
  70354. imageData[(x + width * y) * 4 + 0] = color;
  70355. imageData[(x + width * y) * 4 + 1] = color;
  70356. imageData[(x + width * y) * 4 + 2] = color;
  70357. imageData[(x + width * y) * 4 + 3] = 255;
  70358. }
  70359. }
  70360. return imageData;
  70361. };
  70362. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70363. var image = pixel_data;
  70364. var width = header.width, height = header.height;
  70365. var i = 0, x, y;
  70366. var imageData = new Uint8Array(width * height * 4);
  70367. for (y = y_start; y !== y_end; y += y_step) {
  70368. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70369. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70370. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70372. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70373. }
  70374. }
  70375. return imageData;
  70376. };
  70377. //private static _TYPE_NO_DATA = 0;
  70378. TGATools._TYPE_INDEXED = 1;
  70379. TGATools._TYPE_RGB = 2;
  70380. TGATools._TYPE_GREY = 3;
  70381. TGATools._TYPE_RLE_INDEXED = 9;
  70382. TGATools._TYPE_RLE_RGB = 10;
  70383. TGATools._TYPE_RLE_GREY = 11;
  70384. TGATools._ORIGIN_MASK = 0x30;
  70385. TGATools._ORIGIN_SHIFT = 0x04;
  70386. TGATools._ORIGIN_BL = 0x00;
  70387. TGATools._ORIGIN_BR = 0x01;
  70388. TGATools._ORIGIN_UL = 0x02;
  70389. TGATools._ORIGIN_UR = 0x03;
  70390. return TGATools;
  70391. }());
  70392. BABYLON.TGATools = TGATools;
  70393. })(BABYLON || (BABYLON = {}));
  70394. //# sourceMappingURL=babylon.tga.js.map
  70395. var BABYLON;
  70396. (function (BABYLON) {
  70397. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70398. // All values and structures referenced from:
  70399. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70400. var DDS_MAGIC = 0x20534444;
  70401. var
  70402. //DDSD_CAPS = 0x1,
  70403. //DDSD_HEIGHT = 0x2,
  70404. //DDSD_WIDTH = 0x4,
  70405. //DDSD_PITCH = 0x8,
  70406. //DDSD_PIXELFORMAT = 0x1000,
  70407. DDSD_MIPMAPCOUNT = 0x20000;
  70408. //DDSD_LINEARSIZE = 0x80000,
  70409. //DDSD_DEPTH = 0x800000;
  70410. // var DDSCAPS_COMPLEX = 0x8,
  70411. // DDSCAPS_MIPMAP = 0x400000,
  70412. // DDSCAPS_TEXTURE = 0x1000;
  70413. var DDSCAPS2_CUBEMAP = 0x200;
  70414. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70415. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70416. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70417. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70418. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70419. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70420. // DDSCAPS2_VOLUME = 0x200000;
  70421. var
  70422. //DDPF_ALPHAPIXELS = 0x1,
  70423. //DDPF_ALPHA = 0x2,
  70424. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70425. //DDPF_YUV = 0x200,
  70426. DDPF_LUMINANCE = 0x20000;
  70427. function FourCCToInt32(value) {
  70428. return value.charCodeAt(0) +
  70429. (value.charCodeAt(1) << 8) +
  70430. (value.charCodeAt(2) << 16) +
  70431. (value.charCodeAt(3) << 24);
  70432. }
  70433. function Int32ToFourCC(value) {
  70434. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70435. }
  70436. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70437. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70438. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70439. var FOURCC_DX10 = FourCCToInt32("DX10");
  70440. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70441. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70442. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70443. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70444. var headerLengthInt = 31; // The header length in 32 bit ints
  70445. // Offsets into the header array
  70446. var off_magic = 0;
  70447. var off_size = 1;
  70448. var off_flags = 2;
  70449. var off_height = 3;
  70450. var off_width = 4;
  70451. var off_mipmapCount = 7;
  70452. var off_pfFlags = 20;
  70453. var off_pfFourCC = 21;
  70454. var off_RGBbpp = 22;
  70455. // var off_RMask = 23;
  70456. // var off_GMask = 24;
  70457. // var off_BMask = 25;
  70458. // var off_AMask = 26;
  70459. // var off_caps1 = 27;
  70460. var off_caps2 = 28;
  70461. // var off_caps3 = 29;
  70462. // var off_caps4 = 30;
  70463. var off_dxgiFormat = 32;
  70464. ;
  70465. var DDSTools = /** @class */ (function () {
  70466. function DDSTools() {
  70467. }
  70468. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70469. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70470. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70471. var mipmapCount = 1;
  70472. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70473. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70474. }
  70475. var fourCC = header[off_pfFourCC];
  70476. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70477. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70478. switch (fourCC) {
  70479. case FOURCC_D3DFMT_R16G16B16A16F:
  70480. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70481. break;
  70482. case FOURCC_D3DFMT_R32G32B32A32F:
  70483. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70484. break;
  70485. case FOURCC_DX10:
  70486. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70487. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70488. break;
  70489. }
  70490. }
  70491. return {
  70492. width: header[off_width],
  70493. height: header[off_height],
  70494. mipmapCount: mipmapCount,
  70495. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70496. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70497. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70498. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70499. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70500. dxgiFormat: dxgiFormat,
  70501. textureType: textureType
  70502. };
  70503. };
  70504. DDSTools._ToHalfFloat = function (value) {
  70505. if (!DDSTools._FloatView) {
  70506. DDSTools._FloatView = new Float32Array(1);
  70507. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70508. }
  70509. DDSTools._FloatView[0] = value;
  70510. var x = DDSTools._Int32View[0];
  70511. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70512. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70513. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70514. /* If zero, or denormal, or exponent underflows too much for a denormal
  70515. * half, return signed zero. */
  70516. if (e < 103) {
  70517. return bits;
  70518. }
  70519. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70520. if (e > 142) {
  70521. bits |= 0x7c00;
  70522. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70523. * not Inf, so make sure we set one mantissa bit too. */
  70524. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70525. return bits;
  70526. }
  70527. /* If exponent underflows but not too much, return a denormal */
  70528. if (e < 113) {
  70529. m |= 0x0800;
  70530. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70531. * to 1, which is OK. */
  70532. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70533. return bits;
  70534. }
  70535. bits |= ((e - 112) << 10) | (m >> 1);
  70536. bits += m & 1;
  70537. return bits;
  70538. };
  70539. DDSTools._FromHalfFloat = function (value) {
  70540. var s = (value & 0x8000) >> 15;
  70541. var e = (value & 0x7C00) >> 10;
  70542. var f = value & 0x03FF;
  70543. if (e === 0) {
  70544. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70545. }
  70546. else if (e == 0x1F) {
  70547. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70548. }
  70549. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70550. };
  70551. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70552. var destArray = new Float32Array(dataLength);
  70553. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70554. var index = 0;
  70555. for (var y = 0; y < height; y++) {
  70556. for (var x = 0; x < width; x++) {
  70557. var srcPos = (x + y * width) * 4;
  70558. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70559. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70560. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70561. if (DDSTools.StoreLODInAlphaChannel) {
  70562. destArray[index + 3] = lod;
  70563. }
  70564. else {
  70565. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70566. }
  70567. index += 4;
  70568. }
  70569. }
  70570. return destArray;
  70571. };
  70572. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70573. if (DDSTools.StoreLODInAlphaChannel) {
  70574. var destArray = new Uint16Array(dataLength);
  70575. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70576. var index = 0;
  70577. for (var y = 0; y < height; y++) {
  70578. for (var x = 0; x < width; x++) {
  70579. var srcPos = (x + y * width) * 4;
  70580. destArray[index] = srcData[srcPos];
  70581. destArray[index + 1] = srcData[srcPos + 1];
  70582. destArray[index + 2] = srcData[srcPos + 2];
  70583. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70584. index += 4;
  70585. }
  70586. }
  70587. return destArray;
  70588. }
  70589. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70590. };
  70591. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70592. if (DDSTools.StoreLODInAlphaChannel) {
  70593. var destArray = new Float32Array(dataLength);
  70594. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70595. var index = 0;
  70596. for (var y = 0; y < height; y++) {
  70597. for (var x = 0; x < width; x++) {
  70598. var srcPos = (x + y * width) * 4;
  70599. destArray[index] = srcData[srcPos];
  70600. destArray[index + 1] = srcData[srcPos + 1];
  70601. destArray[index + 2] = srcData[srcPos + 2];
  70602. destArray[index + 3] = lod;
  70603. index += 4;
  70604. }
  70605. }
  70606. return destArray;
  70607. }
  70608. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70609. };
  70610. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70611. var destArray = new Uint8Array(dataLength);
  70612. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70613. var index = 0;
  70614. for (var y = 0; y < height; y++) {
  70615. for (var x = 0; x < width; x++) {
  70616. var srcPos = (x + y * width) * 4;
  70617. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70618. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70619. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70620. if (DDSTools.StoreLODInAlphaChannel) {
  70621. destArray[index + 3] = lod;
  70622. }
  70623. else {
  70624. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70625. }
  70626. index += 4;
  70627. }
  70628. }
  70629. return destArray;
  70630. };
  70631. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70632. var destArray = new Uint8Array(dataLength);
  70633. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70634. var index = 0;
  70635. for (var y = 0; y < height; y++) {
  70636. for (var x = 0; x < width; x++) {
  70637. var srcPos = (x + y * width) * 4;
  70638. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70639. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70640. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70641. if (DDSTools.StoreLODInAlphaChannel) {
  70642. destArray[index + 3] = lod;
  70643. }
  70644. else {
  70645. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70646. }
  70647. index += 4;
  70648. }
  70649. }
  70650. return destArray;
  70651. };
  70652. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70653. var byteArray = new Uint8Array(dataLength);
  70654. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70655. var index = 0;
  70656. for (var y = 0; y < height; y++) {
  70657. for (var x = 0; x < width; x++) {
  70658. var srcPos = (x + y * width) * 4;
  70659. byteArray[index] = srcData[srcPos + 2];
  70660. byteArray[index + 1] = srcData[srcPos + 1];
  70661. byteArray[index + 2] = srcData[srcPos];
  70662. byteArray[index + 3] = srcData[srcPos + 3];
  70663. index += 4;
  70664. }
  70665. }
  70666. return byteArray;
  70667. };
  70668. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70669. var byteArray = new Uint8Array(dataLength);
  70670. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70671. var index = 0;
  70672. for (var y = 0; y < height; y++) {
  70673. for (var x = 0; x < width; x++) {
  70674. var srcPos = (x + y * width) * 3;
  70675. byteArray[index] = srcData[srcPos + 2];
  70676. byteArray[index + 1] = srcData[srcPos + 1];
  70677. byteArray[index + 2] = srcData[srcPos];
  70678. index += 3;
  70679. }
  70680. }
  70681. return byteArray;
  70682. };
  70683. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70684. var byteArray = new Uint8Array(dataLength);
  70685. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70686. var index = 0;
  70687. for (var y = 0; y < height; y++) {
  70688. for (var x = 0; x < width; x++) {
  70689. var srcPos = (x + y * width);
  70690. byteArray[index] = srcData[srcPos];
  70691. index++;
  70692. }
  70693. }
  70694. return byteArray;
  70695. };
  70696. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70697. if (lodIndex === void 0) { lodIndex = -1; }
  70698. var ext = engine.getCaps().s3tc;
  70699. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70700. var fourCC, width, height, dataLength = 0, dataOffset;
  70701. var byteArray, mipmapCount, mip;
  70702. var internalFormat = 0;
  70703. var format = 0;
  70704. var blockBytes = 1;
  70705. if (header[off_magic] !== DDS_MAGIC) {
  70706. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70707. return;
  70708. }
  70709. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70710. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70711. return;
  70712. }
  70713. if (info.isCompressed && !ext) {
  70714. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70715. return;
  70716. }
  70717. var bpp = header[off_RGBbpp];
  70718. dataOffset = header[off_size] + 4;
  70719. var computeFormats = false;
  70720. if (info.isFourCC) {
  70721. fourCC = header[off_pfFourCC];
  70722. switch (fourCC) {
  70723. case FOURCC_DXT1:
  70724. blockBytes = 8;
  70725. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70726. break;
  70727. case FOURCC_DXT3:
  70728. blockBytes = 16;
  70729. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70730. break;
  70731. case FOURCC_DXT5:
  70732. blockBytes = 16;
  70733. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70734. break;
  70735. case FOURCC_D3DFMT_R16G16B16A16F:
  70736. computeFormats = true;
  70737. break;
  70738. case FOURCC_D3DFMT_R32G32B32A32F:
  70739. computeFormats = true;
  70740. break;
  70741. case FOURCC_DX10:
  70742. // There is an additionnal header so dataOffset need to be changed
  70743. dataOffset += 5 * 4; // 5 uints
  70744. var supported = false;
  70745. switch (info.dxgiFormat) {
  70746. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70747. computeFormats = true;
  70748. supported = true;
  70749. break;
  70750. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70751. info.isRGB = true;
  70752. info.isFourCC = false;
  70753. bpp = 32;
  70754. supported = true;
  70755. break;
  70756. }
  70757. if (supported) {
  70758. break;
  70759. }
  70760. default:
  70761. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70762. return;
  70763. }
  70764. }
  70765. if (computeFormats) {
  70766. format = engine._getWebGLTextureType(info.textureType);
  70767. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70768. }
  70769. mipmapCount = 1;
  70770. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70771. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70772. }
  70773. for (var face = 0; face < faces; face++) {
  70774. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70775. width = header[off_width];
  70776. height = header[off_height];
  70777. for (mip = 0; mip < mipmapCount; ++mip) {
  70778. if (lodIndex === -1 || lodIndex === mip) {
  70779. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70780. var i = (lodIndex === -1) ? mip : 0;
  70781. if (!info.isCompressed && info.isFourCC) {
  70782. dataLength = width * height * 4;
  70783. var floatArray = null;
  70784. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70785. if (bpp === 128) {
  70786. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70787. }
  70788. else if (bpp === 64) {
  70789. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70790. }
  70791. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70792. format = engine._getWebGLTextureType(info.textureType);
  70793. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70794. }
  70795. else {
  70796. if (bpp === 128) {
  70797. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70798. }
  70799. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70800. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70801. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70802. format = engine._getWebGLTextureType(info.textureType);
  70803. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70804. }
  70805. else {
  70806. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70807. }
  70808. }
  70809. if (floatArray) {
  70810. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70811. }
  70812. }
  70813. else if (info.isRGB) {
  70814. if (bpp === 24) {
  70815. dataLength = width * height * 3;
  70816. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70817. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70818. }
  70819. else {
  70820. dataLength = width * height * 4;
  70821. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70822. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70823. }
  70824. }
  70825. else if (info.isLuminance) {
  70826. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70827. var unpaddedRowSize = width;
  70828. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70829. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70830. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70831. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70832. }
  70833. else {
  70834. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70835. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70836. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70837. }
  70838. }
  70839. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70840. width *= 0.5;
  70841. height *= 0.5;
  70842. width = Math.max(1.0, width);
  70843. height = Math.max(1.0, height);
  70844. }
  70845. if (currentFace !== undefined) {
  70846. // Loading a single face
  70847. break;
  70848. }
  70849. }
  70850. };
  70851. DDSTools.StoreLODInAlphaChannel = false;
  70852. return DDSTools;
  70853. }());
  70854. BABYLON.DDSTools = DDSTools;
  70855. })(BABYLON || (BABYLON = {}));
  70856. //# sourceMappingURL=babylon.dds.js.map
  70857. var BABYLON;
  70858. (function (BABYLON) {
  70859. /**
  70860. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70861. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70862. */
  70863. var KhronosTextureContainer = /** @class */ (function () {
  70864. /**
  70865. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70866. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70867. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70868. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70869. */
  70870. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70871. this.arrayBuffer = arrayBuffer;
  70872. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70873. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70874. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70875. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70876. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70877. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70878. BABYLON.Tools.Error("texture missing KTX identifier");
  70879. return;
  70880. }
  70881. // load the reset of the header in native 32 bit int
  70882. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70883. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70884. var oppositeEndianess = header[0] === 0x01020304;
  70885. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70886. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70887. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70888. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70889. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70890. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70891. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70892. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70893. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70894. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70895. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70896. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70897. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70898. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70899. if (this.glType !== 0) {
  70900. BABYLON.Tools.Error("only compressed formats currently supported");
  70901. return;
  70902. }
  70903. else {
  70904. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70905. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70906. }
  70907. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70908. BABYLON.Tools.Error("only 2D textures currently supported");
  70909. return;
  70910. }
  70911. if (this.numberOfArrayElements !== 0) {
  70912. BABYLON.Tools.Error("texture arrays not currently supported");
  70913. return;
  70914. }
  70915. if (this.numberOfFaces !== facesExpected) {
  70916. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70917. return;
  70918. }
  70919. // we now have a completely validated file, so could use existence of loadType as success
  70920. // would need to make this more elaborate & adjust checks above to support more than one load type
  70921. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70922. }
  70923. // not as fast hardware based, but will probably never need to use
  70924. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70925. return ((val & 0xFF) << 24)
  70926. | ((val & 0xFF00) << 8)
  70927. | ((val >> 8) & 0xFF00)
  70928. | ((val >> 24) & 0xFF);
  70929. };
  70930. /**
  70931. * It is assumed that the texture has already been created & is currently bound
  70932. */
  70933. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70934. switch (this.loadType) {
  70935. case KhronosTextureContainer.COMPRESSED_2D:
  70936. this._upload2DCompressedLevels(gl, loadMipmaps);
  70937. break;
  70938. case KhronosTextureContainer.TEX_2D:
  70939. case KhronosTextureContainer.COMPRESSED_3D:
  70940. case KhronosTextureContainer.TEX_3D:
  70941. }
  70942. };
  70943. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70944. // initialize width & height for level 1
  70945. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70946. var width = this.pixelWidth;
  70947. var height = this.pixelHeight;
  70948. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70949. for (var level = 0; level < mipmapCount; level++) {
  70950. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70951. for (var face = 0; face < this.numberOfFaces; face++) {
  70952. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70953. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70954. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70955. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70956. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70957. }
  70958. width = Math.max(1.0, width * 0.5);
  70959. height = Math.max(1.0, height * 0.5);
  70960. }
  70961. };
  70962. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70963. // load types
  70964. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70965. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70966. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  70967. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  70968. return KhronosTextureContainer;
  70969. }());
  70970. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  70971. })(BABYLON || (BABYLON = {}));
  70972. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  70973. var BABYLON;
  70974. (function (BABYLON) {
  70975. var Debug = /** @class */ (function () {
  70976. function Debug() {
  70977. }
  70978. Debug.AxesViewer = /** @class */ (function () {
  70979. function AxesViewer(scene, scaleLines) {
  70980. if (scaleLines === void 0) { scaleLines = 1; }
  70981. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70982. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70983. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70984. this.scaleLines = 1;
  70985. this.scaleLines = scaleLines;
  70986. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  70987. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  70988. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  70989. this._xmesh.renderingGroupId = 2;
  70990. this._ymesh.renderingGroupId = 2;
  70991. this._zmesh.renderingGroupId = 2;
  70992. this._xmesh.material.checkReadyOnlyOnce = true;
  70993. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  70994. this._ymesh.material.checkReadyOnlyOnce = true;
  70995. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  70996. this._zmesh.material.checkReadyOnlyOnce = true;
  70997. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  70998. this.scene = scene;
  70999. }
  71000. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71001. var scaleLines = this.scaleLines;
  71002. if (this._xmesh) {
  71003. this._xmesh.position.copyFrom(position);
  71004. }
  71005. if (this._ymesh) {
  71006. this._ymesh.position.copyFrom(position);
  71007. }
  71008. if (this._zmesh) {
  71009. this._zmesh.position.copyFrom(position);
  71010. }
  71011. var point2 = this._xline[1];
  71012. point2.x = xaxis.x * scaleLines;
  71013. point2.y = xaxis.y * scaleLines;
  71014. point2.z = xaxis.z * scaleLines;
  71015. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71016. point2 = this._yline[1];
  71017. point2.x = yaxis.x * scaleLines;
  71018. point2.y = yaxis.y * scaleLines;
  71019. point2.z = yaxis.z * scaleLines;
  71020. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71021. point2 = this._zline[1];
  71022. point2.x = zaxis.x * scaleLines;
  71023. point2.y = zaxis.y * scaleLines;
  71024. point2.z = zaxis.z * scaleLines;
  71025. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71026. };
  71027. AxesViewer.prototype.dispose = function () {
  71028. if (this._xmesh) {
  71029. this._xmesh.dispose();
  71030. }
  71031. if (this._ymesh) {
  71032. this._ymesh.dispose();
  71033. }
  71034. if (this._zmesh) {
  71035. this._zmesh.dispose();
  71036. }
  71037. this._xmesh = null;
  71038. this._ymesh = null;
  71039. this._zmesh = null;
  71040. this.scene = null;
  71041. };
  71042. return AxesViewer;
  71043. }());
  71044. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71045. __extends(BoneAxesViewer, _super);
  71046. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71047. if (scaleLines === void 0) { scaleLines = 1; }
  71048. var _this = _super.call(this, scene, scaleLines) || this;
  71049. _this.pos = BABYLON.Vector3.Zero();
  71050. _this.xaxis = BABYLON.Vector3.Zero();
  71051. _this.yaxis = BABYLON.Vector3.Zero();
  71052. _this.zaxis = BABYLON.Vector3.Zero();
  71053. _this.mesh = mesh;
  71054. _this.bone = bone;
  71055. return _this;
  71056. }
  71057. BoneAxesViewer.prototype.update = function () {
  71058. if (!this.mesh || !this.bone) {
  71059. return;
  71060. }
  71061. var bone = this.bone;
  71062. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71063. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71064. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71065. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71066. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71067. };
  71068. BoneAxesViewer.prototype.dispose = function () {
  71069. if (this.mesh) {
  71070. this.mesh = null;
  71071. this.bone = null;
  71072. _super.prototype.dispose.call(this);
  71073. }
  71074. };
  71075. return BoneAxesViewer;
  71076. }(Debug.AxesViewer));
  71077. Debug.PhysicsViewer = /** @class */ (function () {
  71078. function PhysicsViewer(scene) {
  71079. this._impostors = [];
  71080. this._meshes = [];
  71081. this._numMeshes = 0;
  71082. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71083. var physicEngine = this._scene.getPhysicsEngine();
  71084. if (physicEngine) {
  71085. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71086. }
  71087. }
  71088. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71089. var plugin = this._physicsEnginePlugin;
  71090. for (var i = 0; i < this._numMeshes; i++) {
  71091. var impostor = this._impostors[i];
  71092. if (!impostor) {
  71093. continue;
  71094. }
  71095. if (impostor.isDisposed) {
  71096. this.hideImpostor(this._impostors[i--]);
  71097. }
  71098. else {
  71099. var mesh = this._meshes[i];
  71100. if (mesh && plugin) {
  71101. plugin.syncMeshWithImpostor(mesh, impostor);
  71102. }
  71103. }
  71104. }
  71105. };
  71106. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71107. if (!this._scene) {
  71108. return;
  71109. }
  71110. for (var i = 0; i < this._numMeshes; i++) {
  71111. if (this._impostors[i] == impostor) {
  71112. return;
  71113. }
  71114. }
  71115. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71116. if (debugMesh) {
  71117. this._impostors[this._numMeshes] = impostor;
  71118. this._meshes[this._numMeshes] = debugMesh;
  71119. if (this._numMeshes === 0) {
  71120. this._renderFunction = this._updateDebugMeshes.bind(this);
  71121. this._scene.registerBeforeRender(this._renderFunction);
  71122. }
  71123. this._numMeshes++;
  71124. }
  71125. };
  71126. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71127. if (!impostor || !this._scene) {
  71128. return;
  71129. }
  71130. var removed = false;
  71131. for (var i = 0; i < this._numMeshes; i++) {
  71132. if (this._impostors[i] == impostor) {
  71133. var mesh = this._meshes[i];
  71134. if (!mesh) {
  71135. continue;
  71136. }
  71137. this._scene.removeMesh(mesh);
  71138. mesh.dispose();
  71139. this._numMeshes--;
  71140. if (this._numMeshes > 0) {
  71141. this._meshes[i] = this._meshes[this._numMeshes];
  71142. this._impostors[i] = this._impostors[this._numMeshes];
  71143. this._meshes[this._numMeshes] = null;
  71144. this._impostors[this._numMeshes] = null;
  71145. }
  71146. else {
  71147. this._meshes[0] = null;
  71148. this._impostors[0] = null;
  71149. }
  71150. removed = true;
  71151. break;
  71152. }
  71153. }
  71154. if (removed && this._numMeshes === 0) {
  71155. this._scene.unregisterBeforeRender(this._renderFunction);
  71156. }
  71157. };
  71158. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71159. if (!this._debugMaterial) {
  71160. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71161. this._debugMaterial.wireframe = true;
  71162. }
  71163. return this._debugMaterial;
  71164. };
  71165. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71166. if (!this._debugBoxMesh) {
  71167. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71168. this._debugBoxMesh.renderingGroupId = 1;
  71169. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71170. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71171. scene.removeMesh(this._debugBoxMesh);
  71172. }
  71173. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71174. };
  71175. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71176. if (!this._debugSphereMesh) {
  71177. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71178. this._debugSphereMesh.renderingGroupId = 1;
  71179. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71180. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71181. scene.removeMesh(this._debugSphereMesh);
  71182. }
  71183. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71184. };
  71185. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71186. var mesh = null;
  71187. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71188. mesh = this._getDebugBoxMesh(scene);
  71189. impostor.getBoxSizeToRef(mesh.scaling);
  71190. }
  71191. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71192. mesh = this._getDebugSphereMesh(scene);
  71193. var radius = impostor.getRadius();
  71194. mesh.scaling.x = radius * 2;
  71195. mesh.scaling.y = radius * 2;
  71196. mesh.scaling.z = radius * 2;
  71197. }
  71198. return mesh;
  71199. };
  71200. PhysicsViewer.prototype.dispose = function () {
  71201. for (var i = 0; i < this._numMeshes; i++) {
  71202. this.hideImpostor(this._impostors[i]);
  71203. }
  71204. if (this._debugBoxMesh) {
  71205. this._debugBoxMesh.dispose();
  71206. }
  71207. if (this._debugSphereMesh) {
  71208. this._debugSphereMesh.dispose();
  71209. }
  71210. if (this._debugMaterial) {
  71211. this._debugMaterial.dispose();
  71212. }
  71213. this._impostors.length = 0;
  71214. this._scene = null;
  71215. this._physicsEnginePlugin = null;
  71216. };
  71217. return PhysicsViewer;
  71218. }());
  71219. Debug.SkeletonViewer = /** @class */ (function () {
  71220. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71221. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71222. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71223. this.skeleton = skeleton;
  71224. this.mesh = mesh;
  71225. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71226. this.renderingGroupId = renderingGroupId;
  71227. this.color = BABYLON.Color3.White();
  71228. this._debugLines = new Array();
  71229. this._isEnabled = false;
  71230. this._scene = scene;
  71231. this.update();
  71232. this._renderFunction = this.update.bind(this);
  71233. }
  71234. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71235. get: function () {
  71236. return this._isEnabled;
  71237. },
  71238. set: function (value) {
  71239. if (this._isEnabled === value) {
  71240. return;
  71241. }
  71242. this._isEnabled = value;
  71243. if (value) {
  71244. this._scene.registerBeforeRender(this._renderFunction);
  71245. }
  71246. else {
  71247. this._scene.unregisterBeforeRender(this._renderFunction);
  71248. }
  71249. },
  71250. enumerable: true,
  71251. configurable: true
  71252. });
  71253. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71254. if (x === void 0) { x = 0; }
  71255. if (y === void 0) { y = 0; }
  71256. if (z === void 0) { z = 0; }
  71257. var tmat = BABYLON.Tmp.Matrix[0];
  71258. var parentBone = bone.getParent();
  71259. tmat.copyFrom(bone.getLocalMatrix());
  71260. if (x !== 0 || y !== 0 || z !== 0) {
  71261. var tmat2 = BABYLON.Tmp.Matrix[1];
  71262. BABYLON.Matrix.IdentityToRef(tmat2);
  71263. tmat2.m[12] = x;
  71264. tmat2.m[13] = y;
  71265. tmat2.m[14] = z;
  71266. tmat2.multiplyToRef(tmat, tmat);
  71267. }
  71268. if (parentBone) {
  71269. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71270. }
  71271. tmat.multiplyToRef(meshMat, tmat);
  71272. position.x = tmat.m[12];
  71273. position.y = tmat.m[13];
  71274. position.z = tmat.m[14];
  71275. };
  71276. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71277. var len = bones.length;
  71278. var meshPos = this.mesh.position;
  71279. for (var i = 0; i < len; i++) {
  71280. var bone = bones[i];
  71281. var points = this._debugLines[i];
  71282. if (!points) {
  71283. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71284. this._debugLines[i] = points;
  71285. }
  71286. this._getBonePosition(points[0], bone, meshMat);
  71287. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71288. points[0].subtractInPlace(meshPos);
  71289. points[1].subtractInPlace(meshPos);
  71290. }
  71291. };
  71292. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71293. var len = bones.length;
  71294. var boneNum = 0;
  71295. var meshPos = this.mesh.position;
  71296. for (var i = len - 1; i >= 0; i--) {
  71297. var childBone = bones[i];
  71298. var parentBone = childBone.getParent();
  71299. if (!parentBone) {
  71300. continue;
  71301. }
  71302. var points = this._debugLines[boneNum];
  71303. if (!points) {
  71304. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71305. this._debugLines[boneNum] = points;
  71306. }
  71307. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71308. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71309. points[0].subtractInPlace(meshPos);
  71310. points[1].subtractInPlace(meshPos);
  71311. boneNum++;
  71312. }
  71313. };
  71314. SkeletonViewer.prototype.update = function () {
  71315. if (this.autoUpdateBonesMatrices) {
  71316. this.skeleton.computeAbsoluteTransforms();
  71317. }
  71318. if (this.skeleton.bones[0].length === undefined) {
  71319. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71320. }
  71321. else {
  71322. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71323. }
  71324. if (!this._debugMesh) {
  71325. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71326. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71327. }
  71328. else {
  71329. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71330. }
  71331. this._debugMesh.position.copyFrom(this.mesh.position);
  71332. this._debugMesh.color = this.color;
  71333. };
  71334. SkeletonViewer.prototype.dispose = function () {
  71335. if (this._debugMesh) {
  71336. this.isEnabled = false;
  71337. this._debugMesh.dispose();
  71338. this._debugMesh = null;
  71339. }
  71340. };
  71341. return SkeletonViewer;
  71342. }());
  71343. return Debug;
  71344. }());
  71345. BABYLON.Debug = Debug;
  71346. })(BABYLON || (BABYLON = {}));
  71347. //# sourceMappingURL=babylon.debugModules.js.map
  71348. var BABYLON;
  71349. (function (BABYLON) {
  71350. var RayHelper = /** @class */ (function () {
  71351. function RayHelper(ray) {
  71352. this.ray = ray;
  71353. }
  71354. RayHelper.CreateAndShow = function (ray, scene, color) {
  71355. var helper = new RayHelper(ray);
  71356. helper.show(scene, color);
  71357. return helper;
  71358. };
  71359. RayHelper.prototype.show = function (scene, color) {
  71360. if (!this._renderFunction && this.ray) {
  71361. var ray = this.ray;
  71362. this._renderFunction = this._render.bind(this);
  71363. this._scene = scene;
  71364. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71365. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71366. if (this._renderFunction) {
  71367. this._scene.registerBeforeRender(this._renderFunction);
  71368. }
  71369. }
  71370. if (color && this._renderLine) {
  71371. this._renderLine.color.copyFrom(color);
  71372. }
  71373. };
  71374. RayHelper.prototype.hide = function () {
  71375. if (this._renderFunction && this._scene) {
  71376. this._scene.unregisterBeforeRender(this._renderFunction);
  71377. this._scene = null;
  71378. this._renderFunction = null;
  71379. if (this._renderLine) {
  71380. this._renderLine.dispose();
  71381. this._renderLine = null;
  71382. }
  71383. this._renderPoints = [];
  71384. }
  71385. };
  71386. RayHelper.prototype._render = function () {
  71387. var ray = this.ray;
  71388. if (!ray) {
  71389. return;
  71390. }
  71391. var point = this._renderPoints[1];
  71392. var len = Math.min(ray.length, 1000000);
  71393. point.copyFrom(ray.direction);
  71394. point.scaleInPlace(len);
  71395. point.addInPlace(ray.origin);
  71396. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71397. };
  71398. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71399. this._attachedToMesh = mesh;
  71400. var ray = this.ray;
  71401. if (!ray) {
  71402. return;
  71403. }
  71404. if (!ray.direction) {
  71405. ray.direction = BABYLON.Vector3.Zero();
  71406. }
  71407. if (!ray.origin) {
  71408. ray.origin = BABYLON.Vector3.Zero();
  71409. }
  71410. if (length) {
  71411. ray.length = length;
  71412. }
  71413. if (!meshSpaceOrigin) {
  71414. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71415. }
  71416. if (!meshSpaceDirection) {
  71417. // -1 so that this will work with Mesh.lookAt
  71418. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71419. }
  71420. if (!this._meshSpaceDirection) {
  71421. this._meshSpaceDirection = meshSpaceDirection.clone();
  71422. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71423. }
  71424. else {
  71425. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71426. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71427. }
  71428. if (!this._updateToMeshFunction) {
  71429. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71430. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71431. }
  71432. this._updateToMesh();
  71433. };
  71434. RayHelper.prototype.detachFromMesh = function () {
  71435. if (this._attachedToMesh) {
  71436. if (this._updateToMeshFunction) {
  71437. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71438. }
  71439. this._attachedToMesh = null;
  71440. this._updateToMeshFunction = null;
  71441. }
  71442. };
  71443. RayHelper.prototype._updateToMesh = function () {
  71444. var ray = this.ray;
  71445. if (!this._attachedToMesh || !ray) {
  71446. return;
  71447. }
  71448. if (this._attachedToMesh._isDisposed) {
  71449. this.detachFromMesh();
  71450. return;
  71451. }
  71452. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71453. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71454. };
  71455. RayHelper.prototype.dispose = function () {
  71456. this.hide();
  71457. this.detachFromMesh();
  71458. this.ray = null;
  71459. };
  71460. return RayHelper;
  71461. }());
  71462. BABYLON.RayHelper = RayHelper;
  71463. })(BABYLON || (BABYLON = {}));
  71464. //# sourceMappingURL=babylon.rayHelper.js.map
  71465. var BABYLON;
  71466. (function (BABYLON) {
  71467. // load the inspector using require, if not present in the global namespace.
  71468. var DebugLayer = /** @class */ (function () {
  71469. function DebugLayer(scene) {
  71470. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71471. this._scene = scene;
  71472. // load inspector using require, if it doesn't exist on the global namespace.
  71473. }
  71474. /** Creates the inspector window. */
  71475. DebugLayer.prototype._createInspector = function (config) {
  71476. if (config === void 0) { config = {}; }
  71477. var popup = config.popup || false;
  71478. var initialTab = config.initialTab || 0;
  71479. var parentElement = config.parentElement || null;
  71480. if (!this._inspector) {
  71481. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71482. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71483. } // else nothing to do,; instance is already existing
  71484. };
  71485. DebugLayer.prototype.isVisible = function () {
  71486. if (!this._inspector) {
  71487. return false;
  71488. }
  71489. return true;
  71490. };
  71491. DebugLayer.prototype.hide = function () {
  71492. if (this._inspector) {
  71493. try {
  71494. this._inspector.dispose();
  71495. }
  71496. catch (e) {
  71497. // If the inspector has been removed directly from the inspector tool
  71498. }
  71499. this._inspector = null;
  71500. }
  71501. };
  71502. DebugLayer.prototype.show = function (config) {
  71503. if (config === void 0) { config = {}; }
  71504. if (typeof this.BJSINSPECTOR == 'undefined') {
  71505. // Load inspector and add it to the DOM
  71506. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71507. }
  71508. else {
  71509. // Otherwise creates the inspector
  71510. this._createInspector(config);
  71511. }
  71512. };
  71513. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71514. return DebugLayer;
  71515. }());
  71516. BABYLON.DebugLayer = DebugLayer;
  71517. })(BABYLON || (BABYLON = {}));
  71518. //# sourceMappingURL=babylon.debugLayer.js.map
  71519. var BABYLON;
  71520. (function (BABYLON) {
  71521. var BoundingBoxRenderer = /** @class */ (function () {
  71522. function BoundingBoxRenderer(scene) {
  71523. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71524. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71525. this.showBackLines = true;
  71526. this.renderList = new BABYLON.SmartArray(32);
  71527. this._vertexBuffers = {};
  71528. this._scene = scene;
  71529. }
  71530. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71531. if (this._colorShader) {
  71532. return;
  71533. }
  71534. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71535. attributes: [BABYLON.VertexBuffer.PositionKind],
  71536. uniforms: ["world", "viewProjection", "color"]
  71537. });
  71538. var engine = this._scene.getEngine();
  71539. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71540. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71541. this._createIndexBuffer();
  71542. };
  71543. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71544. var engine = this._scene.getEngine();
  71545. 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]);
  71546. };
  71547. BoundingBoxRenderer.prototype._rebuild = function () {
  71548. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71549. if (vb) {
  71550. vb._rebuild();
  71551. }
  71552. this._createIndexBuffer();
  71553. };
  71554. BoundingBoxRenderer.prototype.reset = function () {
  71555. this.renderList.reset();
  71556. };
  71557. BoundingBoxRenderer.prototype.render = function () {
  71558. if (this.renderList.length === 0) {
  71559. return;
  71560. }
  71561. this._prepareRessources();
  71562. if (!this._colorShader.isReady()) {
  71563. return;
  71564. }
  71565. var engine = this._scene.getEngine();
  71566. engine.setDepthWrite(false);
  71567. this._colorShader._preBind();
  71568. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71569. var boundingBox = this.renderList.data[boundingBoxIndex];
  71570. var min = boundingBox.minimum;
  71571. var max = boundingBox.maximum;
  71572. var diff = max.subtract(min);
  71573. var median = min.add(diff.scale(0.5));
  71574. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71575. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71576. .multiply(boundingBox.getWorldMatrix());
  71577. // VBOs
  71578. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71579. if (this.showBackLines) {
  71580. // Back
  71581. engine.setDepthFunctionToGreaterOrEqual();
  71582. this._scene.resetCachedMaterial();
  71583. this._colorShader.setColor4("color", this.backColor.toColor4());
  71584. this._colorShader.bind(worldMatrix);
  71585. // Draw order
  71586. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71587. }
  71588. // Front
  71589. engine.setDepthFunctionToLess();
  71590. this._scene.resetCachedMaterial();
  71591. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71592. this._colorShader.bind(worldMatrix);
  71593. // Draw order
  71594. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71595. }
  71596. this._colorShader.unbind();
  71597. engine.setDepthFunctionToLessOrEqual();
  71598. engine.setDepthWrite(true);
  71599. };
  71600. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71601. this._prepareRessources();
  71602. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71603. return;
  71604. }
  71605. var engine = this._scene.getEngine();
  71606. engine.setDepthWrite(false);
  71607. engine.setColorWrite(false);
  71608. this._colorShader._preBind();
  71609. var boundingBox = mesh._boundingInfo.boundingBox;
  71610. var min = boundingBox.minimum;
  71611. var max = boundingBox.maximum;
  71612. var diff = max.subtract(min);
  71613. var median = min.add(diff.scale(0.5));
  71614. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71615. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71616. .multiply(boundingBox.getWorldMatrix());
  71617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71618. engine.setDepthFunctionToLess();
  71619. this._scene.resetCachedMaterial();
  71620. this._colorShader.bind(worldMatrix);
  71621. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71622. this._colorShader.unbind();
  71623. engine.setDepthFunctionToLessOrEqual();
  71624. engine.setDepthWrite(true);
  71625. engine.setColorWrite(true);
  71626. };
  71627. BoundingBoxRenderer.prototype.dispose = function () {
  71628. if (!this._colorShader) {
  71629. return;
  71630. }
  71631. this.renderList.dispose();
  71632. this._colorShader.dispose();
  71633. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71634. if (buffer) {
  71635. buffer.dispose();
  71636. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71637. }
  71638. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71639. };
  71640. return BoundingBoxRenderer;
  71641. }());
  71642. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71643. })(BABYLON || (BABYLON = {}));
  71644. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71645. var BABYLON;
  71646. (function (BABYLON) {
  71647. var MorphTarget = /** @class */ (function () {
  71648. function MorphTarget(name, influence) {
  71649. if (influence === void 0) { influence = 0; }
  71650. this.name = name;
  71651. this.animations = new Array();
  71652. this._positions = null;
  71653. this._normals = null;
  71654. this._tangents = null;
  71655. this.onInfluenceChanged = new BABYLON.Observable();
  71656. this.influence = influence;
  71657. }
  71658. Object.defineProperty(MorphTarget.prototype, "influence", {
  71659. get: function () {
  71660. return this._influence;
  71661. },
  71662. set: function (influence) {
  71663. if (this._influence === influence) {
  71664. return;
  71665. }
  71666. var previous = this._influence;
  71667. this._influence = influence;
  71668. if (this.onInfluenceChanged.hasObservers) {
  71669. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71670. }
  71671. },
  71672. enumerable: true,
  71673. configurable: true
  71674. });
  71675. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71676. get: function () {
  71677. return !!this._positions;
  71678. },
  71679. enumerable: true,
  71680. configurable: true
  71681. });
  71682. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71683. get: function () {
  71684. return !!this._normals;
  71685. },
  71686. enumerable: true,
  71687. configurable: true
  71688. });
  71689. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71690. get: function () {
  71691. return !!this._tangents;
  71692. },
  71693. enumerable: true,
  71694. configurable: true
  71695. });
  71696. MorphTarget.prototype.setPositions = function (data) {
  71697. this._positions = data;
  71698. };
  71699. MorphTarget.prototype.getPositions = function () {
  71700. return this._positions;
  71701. };
  71702. MorphTarget.prototype.setNormals = function (data) {
  71703. this._normals = data;
  71704. };
  71705. MorphTarget.prototype.getNormals = function () {
  71706. return this._normals;
  71707. };
  71708. MorphTarget.prototype.setTangents = function (data) {
  71709. this._tangents = data;
  71710. };
  71711. MorphTarget.prototype.getTangents = function () {
  71712. return this._tangents;
  71713. };
  71714. /**
  71715. * Serializes the current target into a Serialization object.
  71716. * Returns the serialized object.
  71717. */
  71718. MorphTarget.prototype.serialize = function () {
  71719. var serializationObject = {};
  71720. serializationObject.name = this.name;
  71721. serializationObject.influence = this.influence;
  71722. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71723. if (this.hasNormals) {
  71724. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71725. }
  71726. if (this.hasTangents) {
  71727. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71728. }
  71729. // Animations
  71730. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71731. return serializationObject;
  71732. };
  71733. // Statics
  71734. MorphTarget.Parse = function (serializationObject) {
  71735. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71736. result.setPositions(serializationObject.positions);
  71737. if (serializationObject.normals) {
  71738. result.setNormals(serializationObject.normals);
  71739. }
  71740. if (serializationObject.tangents) {
  71741. result.setTangents(serializationObject.tangents);
  71742. }
  71743. // Animations
  71744. if (serializationObject.animations) {
  71745. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71746. var parsedAnimation = serializationObject.animations[animationIndex];
  71747. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71748. }
  71749. }
  71750. return result;
  71751. };
  71752. MorphTarget.FromMesh = function (mesh, name, influence) {
  71753. if (!name) {
  71754. name = mesh.name;
  71755. }
  71756. var result = new MorphTarget(name, influence);
  71757. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71759. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71760. }
  71761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71762. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71763. }
  71764. return result;
  71765. };
  71766. return MorphTarget;
  71767. }());
  71768. BABYLON.MorphTarget = MorphTarget;
  71769. })(BABYLON || (BABYLON = {}));
  71770. //# sourceMappingURL=babylon.morphTarget.js.map
  71771. var BABYLON;
  71772. (function (BABYLON) {
  71773. var MorphTargetManager = /** @class */ (function () {
  71774. function MorphTargetManager(scene) {
  71775. if (scene === void 0) { scene = null; }
  71776. this._targets = new Array();
  71777. this._targetObservable = new Array();
  71778. this._activeTargets = new BABYLON.SmartArray(16);
  71779. this._supportsNormals = false;
  71780. this._supportsTangents = false;
  71781. this._vertexCount = 0;
  71782. this._uniqueId = 0;
  71783. this._tempInfluences = new Array();
  71784. if (!scene) {
  71785. scene = BABYLON.Engine.LastCreatedScene;
  71786. }
  71787. this._scene = scene;
  71788. if (this._scene) {
  71789. this._scene.morphTargetManagers.push(this);
  71790. this._uniqueId = this._scene.getUniqueId();
  71791. }
  71792. }
  71793. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71794. get: function () {
  71795. return this._uniqueId;
  71796. },
  71797. enumerable: true,
  71798. configurable: true
  71799. });
  71800. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71801. get: function () {
  71802. return this._vertexCount;
  71803. },
  71804. enumerable: true,
  71805. configurable: true
  71806. });
  71807. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71808. get: function () {
  71809. return this._supportsNormals;
  71810. },
  71811. enumerable: true,
  71812. configurable: true
  71813. });
  71814. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71815. get: function () {
  71816. return this._supportsTangents;
  71817. },
  71818. enumerable: true,
  71819. configurable: true
  71820. });
  71821. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71822. get: function () {
  71823. return this._targets.length;
  71824. },
  71825. enumerable: true,
  71826. configurable: true
  71827. });
  71828. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71829. get: function () {
  71830. return this._activeTargets.length;
  71831. },
  71832. enumerable: true,
  71833. configurable: true
  71834. });
  71835. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71836. get: function () {
  71837. return this._influences;
  71838. },
  71839. enumerable: true,
  71840. configurable: true
  71841. });
  71842. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71843. return this._activeTargets.data[index];
  71844. };
  71845. MorphTargetManager.prototype.getTarget = function (index) {
  71846. return this._targets[index];
  71847. };
  71848. MorphTargetManager.prototype.addTarget = function (target) {
  71849. var _this = this;
  71850. this._targets.push(target);
  71851. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71852. _this._syncActiveTargets(needUpdate);
  71853. }));
  71854. this._syncActiveTargets(true);
  71855. };
  71856. MorphTargetManager.prototype.removeTarget = function (target) {
  71857. var index = this._targets.indexOf(target);
  71858. if (index >= 0) {
  71859. this._targets.splice(index, 1);
  71860. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71861. this._syncActiveTargets(true);
  71862. }
  71863. };
  71864. /**
  71865. * Serializes the current manager into a Serialization object.
  71866. * Returns the serialized object.
  71867. */
  71868. MorphTargetManager.prototype.serialize = function () {
  71869. var serializationObject = {};
  71870. serializationObject.id = this.uniqueId;
  71871. serializationObject.targets = [];
  71872. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71873. var target = _a[_i];
  71874. serializationObject.targets.push(target.serialize());
  71875. }
  71876. return serializationObject;
  71877. };
  71878. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71879. var influenceCount = 0;
  71880. this._activeTargets.reset();
  71881. this._supportsNormals = true;
  71882. this._supportsTangents = true;
  71883. this._vertexCount = 0;
  71884. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71885. var target = _a[_i];
  71886. this._activeTargets.push(target);
  71887. this._tempInfluences[influenceCount++] = target.influence;
  71888. var positions = target.getPositions();
  71889. if (positions) {
  71890. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71891. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71892. var vertexCount = positions.length / 3;
  71893. if (this._vertexCount === 0) {
  71894. this._vertexCount = vertexCount;
  71895. }
  71896. else if (this._vertexCount !== vertexCount) {
  71897. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71898. return;
  71899. }
  71900. }
  71901. }
  71902. if (!this._influences || this._influences.length !== influenceCount) {
  71903. this._influences = new Float32Array(influenceCount);
  71904. }
  71905. for (var index = 0; index < influenceCount; index++) {
  71906. this._influences[index] = this._tempInfluences[index];
  71907. }
  71908. if (needUpdate && this._scene) {
  71909. // Flag meshes as dirty to resync with the active targets
  71910. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71911. var mesh = _c[_b];
  71912. if (mesh.morphTargetManager === this) {
  71913. mesh._syncGeometryWithMorphTargetManager();
  71914. }
  71915. }
  71916. }
  71917. };
  71918. // Statics
  71919. MorphTargetManager.Parse = function (serializationObject, scene) {
  71920. var result = new MorphTargetManager(scene);
  71921. result._uniqueId = serializationObject.id;
  71922. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71923. var targetData = _a[_i];
  71924. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71925. }
  71926. return result;
  71927. };
  71928. return MorphTargetManager;
  71929. }());
  71930. BABYLON.MorphTargetManager = MorphTargetManager;
  71931. })(BABYLON || (BABYLON = {}));
  71932. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71933. var BABYLON;
  71934. (function (BABYLON) {
  71935. var Octree = /** @class */ (function () {
  71936. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71937. if (maxDepth === void 0) { maxDepth = 2; }
  71938. this.maxDepth = maxDepth;
  71939. this.dynamicContent = new Array();
  71940. this._maxBlockCapacity = maxBlockCapacity || 64;
  71941. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71942. this._creationFunc = creationFunc;
  71943. }
  71944. // Methods
  71945. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71946. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71947. };
  71948. Octree.prototype.addMesh = function (entry) {
  71949. for (var index = 0; index < this.blocks.length; index++) {
  71950. var block = this.blocks[index];
  71951. block.addEntry(entry);
  71952. }
  71953. };
  71954. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71955. this._selectionContent.reset();
  71956. for (var index = 0; index < this.blocks.length; index++) {
  71957. var block = this.blocks[index];
  71958. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71959. }
  71960. if (allowDuplicate) {
  71961. this._selectionContent.concat(this.dynamicContent);
  71962. }
  71963. else {
  71964. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71965. }
  71966. return this._selectionContent;
  71967. };
  71968. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  71969. this._selectionContent.reset();
  71970. for (var index = 0; index < this.blocks.length; index++) {
  71971. var block = this.blocks[index];
  71972. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  71973. }
  71974. if (allowDuplicate) {
  71975. this._selectionContent.concat(this.dynamicContent);
  71976. }
  71977. else {
  71978. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71979. }
  71980. return this._selectionContent;
  71981. };
  71982. Octree.prototype.intersectsRay = function (ray) {
  71983. this._selectionContent.reset();
  71984. for (var index = 0; index < this.blocks.length; index++) {
  71985. var block = this.blocks[index];
  71986. block.intersectsRay(ray, this._selectionContent);
  71987. }
  71988. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71989. return this._selectionContent;
  71990. };
  71991. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  71992. target.blocks = new Array();
  71993. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  71994. // Segmenting space
  71995. for (var x = 0; x < 2; x++) {
  71996. for (var y = 0; y < 2; y++) {
  71997. for (var z = 0; z < 2; z++) {
  71998. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  71999. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72000. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72001. block.addEntries(entries);
  72002. target.blocks.push(block);
  72003. }
  72004. }
  72005. }
  72006. };
  72007. Octree.CreationFuncForMeshes = function (entry, block) {
  72008. var boundingInfo = entry.getBoundingInfo();
  72009. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72010. block.entries.push(entry);
  72011. }
  72012. };
  72013. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72014. var boundingInfo = entry.getBoundingInfo();
  72015. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72016. block.entries.push(entry);
  72017. }
  72018. };
  72019. return Octree;
  72020. }());
  72021. BABYLON.Octree = Octree;
  72022. })(BABYLON || (BABYLON = {}));
  72023. //# sourceMappingURL=babylon.octree.js.map
  72024. var BABYLON;
  72025. (function (BABYLON) {
  72026. var OctreeBlock = /** @class */ (function () {
  72027. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72028. this.entries = new Array();
  72029. this._boundingVectors = new Array();
  72030. this._capacity = capacity;
  72031. this._depth = depth;
  72032. this._maxDepth = maxDepth;
  72033. this._creationFunc = creationFunc;
  72034. this._minPoint = minPoint;
  72035. this._maxPoint = maxPoint;
  72036. this._boundingVectors.push(minPoint.clone());
  72037. this._boundingVectors.push(maxPoint.clone());
  72038. this._boundingVectors.push(minPoint.clone());
  72039. this._boundingVectors[2].x = maxPoint.x;
  72040. this._boundingVectors.push(minPoint.clone());
  72041. this._boundingVectors[3].y = maxPoint.y;
  72042. this._boundingVectors.push(minPoint.clone());
  72043. this._boundingVectors[4].z = maxPoint.z;
  72044. this._boundingVectors.push(maxPoint.clone());
  72045. this._boundingVectors[5].z = minPoint.z;
  72046. this._boundingVectors.push(maxPoint.clone());
  72047. this._boundingVectors[6].x = minPoint.x;
  72048. this._boundingVectors.push(maxPoint.clone());
  72049. this._boundingVectors[7].y = minPoint.y;
  72050. }
  72051. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72052. // Property
  72053. get: function () {
  72054. return this._capacity;
  72055. },
  72056. enumerable: true,
  72057. configurable: true
  72058. });
  72059. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72060. get: function () {
  72061. return this._minPoint;
  72062. },
  72063. enumerable: true,
  72064. configurable: true
  72065. });
  72066. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72067. get: function () {
  72068. return this._maxPoint;
  72069. },
  72070. enumerable: true,
  72071. configurable: true
  72072. });
  72073. // Methods
  72074. OctreeBlock.prototype.addEntry = function (entry) {
  72075. if (this.blocks) {
  72076. for (var index = 0; index < this.blocks.length; index++) {
  72077. var block = this.blocks[index];
  72078. block.addEntry(entry);
  72079. }
  72080. return;
  72081. }
  72082. this._creationFunc(entry, this);
  72083. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72084. this.createInnerBlocks();
  72085. }
  72086. };
  72087. OctreeBlock.prototype.addEntries = function (entries) {
  72088. for (var index = 0; index < entries.length; index++) {
  72089. var mesh = entries[index];
  72090. this.addEntry(mesh);
  72091. }
  72092. };
  72093. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72094. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72095. if (this.blocks) {
  72096. for (var index = 0; index < this.blocks.length; index++) {
  72097. var block = this.blocks[index];
  72098. block.select(frustumPlanes, selection, allowDuplicate);
  72099. }
  72100. return;
  72101. }
  72102. if (allowDuplicate) {
  72103. selection.concat(this.entries);
  72104. }
  72105. else {
  72106. selection.concatWithNoDuplicate(this.entries);
  72107. }
  72108. }
  72109. };
  72110. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72111. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72112. if (this.blocks) {
  72113. for (var index = 0; index < this.blocks.length; index++) {
  72114. var block = this.blocks[index];
  72115. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72116. }
  72117. return;
  72118. }
  72119. if (allowDuplicate) {
  72120. selection.concat(this.entries);
  72121. }
  72122. else {
  72123. selection.concatWithNoDuplicate(this.entries);
  72124. }
  72125. }
  72126. };
  72127. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72128. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72129. if (this.blocks) {
  72130. for (var index = 0; index < this.blocks.length; index++) {
  72131. var block = this.blocks[index];
  72132. block.intersectsRay(ray, selection);
  72133. }
  72134. return;
  72135. }
  72136. selection.concatWithNoDuplicate(this.entries);
  72137. }
  72138. };
  72139. OctreeBlock.prototype.createInnerBlocks = function () {
  72140. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72141. };
  72142. return OctreeBlock;
  72143. }());
  72144. BABYLON.OctreeBlock = OctreeBlock;
  72145. })(BABYLON || (BABYLON = {}));
  72146. //# sourceMappingURL=babylon.octreeBlock.js.map
  72147. var BABYLON;
  72148. (function (BABYLON) {
  72149. var SIMDVector3 = /** @class */ (function () {
  72150. function SIMDVector3() {
  72151. }
  72152. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  72153. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  72154. };
  72155. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  72156. var m = transformation.m;
  72157. var m0 = SIMD.Float32x4.load(m, 0);
  72158. var m1 = SIMD.Float32x4.load(m, 4);
  72159. var m2 = SIMD.Float32x4.load(m, 8);
  72160. var m3 = SIMD.Float32x4.load(m, 12);
  72161. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  72162. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  72163. result.x = SIMD.Float32x4.extractLane(r, 0);
  72164. result.y = SIMD.Float32x4.extractLane(r, 1);
  72165. result.z = SIMD.Float32x4.extractLane(r, 2);
  72166. };
  72167. return SIMDVector3;
  72168. }());
  72169. var SIMDMatrix = /** @class */ (function () {
  72170. function SIMDMatrix() {
  72171. }
  72172. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  72173. var tm = this.m;
  72174. var om = other.m;
  72175. var m0 = SIMD.Float32x4.load(om, 0);
  72176. var m1 = SIMD.Float32x4.load(om, 4);
  72177. var m2 = SIMD.Float32x4.load(om, 8);
  72178. var m3 = SIMD.Float32x4.load(om, 12);
  72179. for (var i = 0; i < 16; i += 4) {
  72180. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  72181. }
  72182. return this;
  72183. };
  72184. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  72185. var src = this.m;
  72186. var dest = other.m;
  72187. // Load the 4 rows
  72188. var src0 = SIMD.Float32x4.load(src, 0);
  72189. var src1 = SIMD.Float32x4.load(src, 4);
  72190. var src2 = SIMD.Float32x4.load(src, 8);
  72191. var src3 = SIMD.Float32x4.load(src, 12);
  72192. // Transpose the source matrix. Sort of. Not a true transpose operation
  72193. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  72194. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  72195. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  72196. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  72197. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  72198. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  72199. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  72200. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  72201. // This is a true transposition, but it will lead to an incorrect result
  72202. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  72203. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  72204. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  72205. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  72206. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  72207. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  72208. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  72209. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  72210. // ----
  72211. tmp1 = SIMD.Float32x4.mul(row2, row3);
  72212. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  72213. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  72214. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  72215. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  72216. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  72217. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  72218. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  72219. // ----
  72220. tmp1 = SIMD.Float32x4.mul(row1, row2);
  72221. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  72222. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  72223. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  72224. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  72225. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  72226. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  72227. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  72228. // ----
  72229. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  72230. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  72231. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  72232. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  72233. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  72234. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  72235. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  72236. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  72237. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  72238. // ----
  72239. tmp1 = SIMD.Float32x4.mul(row0, row1);
  72240. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  72241. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  72242. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  72243. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  72244. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  72245. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  72246. // ----
  72247. tmp1 = SIMD.Float32x4.mul(row0, row3);
  72248. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  72249. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  72250. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  72251. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  72252. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  72253. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  72254. // ----
  72255. tmp1 = SIMD.Float32x4.mul(row0, row2);
  72256. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  72257. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  72258. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  72259. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  72260. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  72261. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  72262. // Compute determinant
  72263. var det = SIMD.Float32x4.mul(row0, minor0);
  72264. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  72265. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  72266. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  72267. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  72268. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  72269. // These shuffles aren't necessary if the faulty transposition is done
  72270. // up at the top of this function.
  72271. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  72272. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  72273. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  72274. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  72275. // Compute final values by multiplying with 1/det
  72276. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  72277. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  72278. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  72279. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  72280. return this;
  72281. };
  72282. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  72283. var out = result.m;
  72284. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  72285. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  72286. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  72287. // cc.kmVec3Subtract(f, pCenter, pEye);
  72288. var f = SIMD.Float32x4.sub(center, eye);
  72289. // cc.kmVec3Normalize(f, f);
  72290. var tmp = SIMD.Float32x4.mul(f, f);
  72291. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72292. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72293. // cc.kmVec3Assign(up, pUp);
  72294. // cc.kmVec3Normalize(up, up);
  72295. tmp = SIMD.Float32x4.mul(up, up);
  72296. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72297. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72298. // cc.kmVec3Cross(s, f, up);
  72299. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  72300. // cc.kmVec3Normalize(s, s);
  72301. tmp = SIMD.Float32x4.mul(s, s);
  72302. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72303. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72304. // cc.kmVec3Cross(u, s, f);
  72305. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  72306. // cc.kmVec3Normalize(s, s);
  72307. tmp = SIMD.Float32x4.mul(s, s);
  72308. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  72309. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  72310. var zero = SIMD.Float32x4.splat(0.0);
  72311. s = SIMD.Float32x4.neg(s);
  72312. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  72313. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  72314. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  72315. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  72316. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  72317. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  72318. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  72319. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  72320. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  72321. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  72322. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  72323. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  72324. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  72325. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  72326. };
  72327. return SIMDMatrix;
  72328. }());
  72329. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  72330. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  72331. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  72332. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  72333. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  72334. var SIMDHelper = /** @class */ (function () {
  72335. function SIMDHelper() {
  72336. }
  72337. Object.defineProperty(SIMDHelper, "IsEnabled", {
  72338. get: function () {
  72339. return SIMDHelper._isEnabled;
  72340. },
  72341. enumerable: true,
  72342. configurable: true
  72343. });
  72344. SIMDHelper.DisableSIMD = function () {
  72345. // Replace functions
  72346. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  72347. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  72348. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  72349. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  72350. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  72351. SIMDHelper._isEnabled = false;
  72352. };
  72353. SIMDHelper.EnableSIMD = function () {
  72354. if (self.SIMD === undefined) {
  72355. return;
  72356. }
  72357. // check if polyfills needed
  72358. if (!self.Math.fround) {
  72359. self.Math.fround = (function (array) { return function (x) {
  72360. return array[0] = x, array[0];
  72361. }; })(new Float32Array(1));
  72362. }
  72363. if (!self.Math.imul) {
  72364. self.Math.imul = function (a, b) {
  72365. var ah = (a >>> 16) & 0xffff;
  72366. var al = a & 0xffff;
  72367. var bh = (b >>> 16) & 0xffff;
  72368. var bl = b & 0xffff;
  72369. // the shift by 0 fixes the sign on the high part
  72370. // the final |0 converts the unsigned value into a signed value
  72371. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  72372. };
  72373. }
  72374. // Replace functions
  72375. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  72376. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  72377. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  72378. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  72379. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  72380. SIMDHelper._isEnabled = true;
  72381. };
  72382. SIMDHelper._isEnabled = false;
  72383. return SIMDHelper;
  72384. }());
  72385. BABYLON.SIMDHelper = SIMDHelper;
  72386. })(BABYLON || (BABYLON = {}));
  72387. //# sourceMappingURL=babylon.math.SIMD.js.map
  72388. var BABYLON;
  72389. (function (BABYLON) {
  72390. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72391. __extends(VRDistortionCorrectionPostProcess, _super);
  72392. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72393. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72394. 'LensCenter',
  72395. 'Scale',
  72396. 'ScaleIn',
  72397. 'HmdWarpParam'
  72398. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72399. _this._isRightEye = isRightEye;
  72400. _this._distortionFactors = vrMetrics.distortionK;
  72401. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72402. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72403. _this.adaptScaleToCurrentViewport = true;
  72404. _this.onSizeChangedObservable.add(function () {
  72405. _this.aspectRatio = _this.width * .5 / _this.height;
  72406. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72407. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72408. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72409. });
  72410. _this.onApplyObservable.add(function (effect) {
  72411. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72412. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72413. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72414. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72415. });
  72416. return _this;
  72417. }
  72418. return VRDistortionCorrectionPostProcess;
  72419. }(BABYLON.PostProcess));
  72420. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72421. })(BABYLON || (BABYLON = {}));
  72422. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72423. var BABYLON;
  72424. (function (BABYLON) {
  72425. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72426. __extends(AnaglyphPostProcess, _super);
  72427. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72428. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72429. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72430. _this.onApplyObservable.add(function (effect) {
  72431. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72432. });
  72433. return _this;
  72434. }
  72435. return AnaglyphPostProcess;
  72436. }(BABYLON.PostProcess));
  72437. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72438. })(BABYLON || (BABYLON = {}));
  72439. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72440. var BABYLON;
  72441. (function (BABYLON) {
  72442. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72443. __extends(StereoscopicInterlacePostProcess, _super);
  72444. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72445. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72446. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72447. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72448. _this.onSizeChangedObservable.add(function () {
  72449. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72450. });
  72451. _this.onApplyObservable.add(function (effect) {
  72452. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72453. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72454. });
  72455. return _this;
  72456. }
  72457. return StereoscopicInterlacePostProcess;
  72458. }(BABYLON.PostProcess));
  72459. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72460. })(BABYLON || (BABYLON = {}));
  72461. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72462. var BABYLON;
  72463. (function (BABYLON) {
  72464. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72465. function FreeCameraDeviceOrientationInput() {
  72466. var _this = this;
  72467. this._screenOrientationAngle = 0;
  72468. this._screenQuaternion = new BABYLON.Quaternion();
  72469. this._alpha = 0;
  72470. this._beta = 0;
  72471. this._gamma = 0;
  72472. this._orientationChanged = function () {
  72473. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72474. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72475. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72476. };
  72477. this._deviceOrientation = function (evt) {
  72478. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72479. _this._beta = evt.beta !== null ? evt.beta : 0;
  72480. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72481. };
  72482. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72483. this._orientationChanged();
  72484. }
  72485. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72486. get: function () {
  72487. return this._camera;
  72488. },
  72489. set: function (camera) {
  72490. this._camera = camera;
  72491. if (this._camera != null && !this._camera.rotationQuaternion) {
  72492. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72493. }
  72494. },
  72495. enumerable: true,
  72496. configurable: true
  72497. });
  72498. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72499. window.addEventListener("orientationchange", this._orientationChanged);
  72500. window.addEventListener("deviceorientation", this._deviceOrientation);
  72501. //In certain cases, the attach control is called AFTER orientation was changed,
  72502. //So this is needed.
  72503. this._orientationChanged();
  72504. };
  72505. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72506. window.removeEventListener("orientationchange", this._orientationChanged);
  72507. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72508. };
  72509. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72510. //if no device orientation provided, don't update the rotation.
  72511. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72512. if (!this._alpha)
  72513. return;
  72514. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72515. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72516. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72517. //Mirror on XY Plane
  72518. this._camera.rotationQuaternion.z *= -1;
  72519. this._camera.rotationQuaternion.w *= -1;
  72520. };
  72521. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72522. return "FreeCameraDeviceOrientationInput";
  72523. };
  72524. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72525. return "deviceOrientation";
  72526. };
  72527. return FreeCameraDeviceOrientationInput;
  72528. }());
  72529. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72530. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72531. })(BABYLON || (BABYLON = {}));
  72532. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72533. var BABYLON;
  72534. (function (BABYLON) {
  72535. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72536. function ArcRotateCameraVRDeviceOrientationInput() {
  72537. this.alphaCorrection = 1;
  72538. this.betaCorrection = 1;
  72539. this.gammaCorrection = 1;
  72540. this._alpha = 0;
  72541. this._gamma = 0;
  72542. this._dirty = false;
  72543. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72544. }
  72545. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72546. this.camera.attachControl(element, noPreventDefault);
  72547. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72548. };
  72549. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72550. if (evt.alpha !== null) {
  72551. this._alpha = +evt.alpha | 0;
  72552. }
  72553. if (evt.gamma !== null) {
  72554. this._gamma = +evt.gamma | 0;
  72555. }
  72556. this._dirty = true;
  72557. };
  72558. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72559. if (this._dirty) {
  72560. this._dirty = false;
  72561. if (this._gamma < 0) {
  72562. this._gamma = 180 + this._gamma;
  72563. }
  72564. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72565. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72566. }
  72567. };
  72568. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72569. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72570. };
  72571. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72572. return "ArcRotateCameraVRDeviceOrientationInput";
  72573. };
  72574. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72575. return "VRDeviceOrientation";
  72576. };
  72577. return ArcRotateCameraVRDeviceOrientationInput;
  72578. }());
  72579. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72580. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72581. })(BABYLON || (BABYLON = {}));
  72582. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72583. var BABYLON;
  72584. (function (BABYLON) {
  72585. var VRCameraMetrics = /** @class */ (function () {
  72586. function VRCameraMetrics() {
  72587. this.compensateDistortion = true;
  72588. }
  72589. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72590. get: function () {
  72591. return this.hResolution / (2 * this.vResolution);
  72592. },
  72593. enumerable: true,
  72594. configurable: true
  72595. });
  72596. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72597. get: function () {
  72598. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72599. },
  72600. enumerable: true,
  72601. configurable: true
  72602. });
  72603. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72604. get: function () {
  72605. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72606. var h = (4 * meters) / this.hScreenSize;
  72607. return BABYLON.Matrix.Translation(h, 0, 0);
  72608. },
  72609. enumerable: true,
  72610. configurable: true
  72611. });
  72612. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72613. get: function () {
  72614. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72615. var h = (4 * meters) / this.hScreenSize;
  72616. return BABYLON.Matrix.Translation(-h, 0, 0);
  72617. },
  72618. enumerable: true,
  72619. configurable: true
  72620. });
  72621. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72622. get: function () {
  72623. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72624. },
  72625. enumerable: true,
  72626. configurable: true
  72627. });
  72628. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72629. get: function () {
  72630. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72631. },
  72632. enumerable: true,
  72633. configurable: true
  72634. });
  72635. VRCameraMetrics.GetDefault = function () {
  72636. var result = new VRCameraMetrics();
  72637. result.hResolution = 1280;
  72638. result.vResolution = 800;
  72639. result.hScreenSize = 0.149759993;
  72640. result.vScreenSize = 0.0935999975;
  72641. result.vScreenCenter = 0.0467999987;
  72642. result.eyeToScreenDistance = 0.0410000011;
  72643. result.lensSeparationDistance = 0.0635000020;
  72644. result.interpupillaryDistance = 0.0640000030;
  72645. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72646. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72647. result.postProcessScaleFactor = 1.714605507808412;
  72648. result.lensCenterOffset = 0.151976421;
  72649. return result;
  72650. };
  72651. return VRCameraMetrics;
  72652. }());
  72653. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72654. })(BABYLON || (BABYLON = {}));
  72655. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72656. var BABYLON;
  72657. (function (BABYLON) {
  72658. var WebVRFreeCamera = /** @class */ (function (_super) {
  72659. __extends(WebVRFreeCamera, _super);
  72660. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72661. if (webVROptions === void 0) { webVROptions = {}; }
  72662. var _this = _super.call(this, name, position, scene) || this;
  72663. _this.webVROptions = webVROptions;
  72664. _this._vrDevice = null;
  72665. _this.rawPose = null;
  72666. _this._specsVersion = "1.1";
  72667. _this._attached = false;
  72668. _this._descendants = [];
  72669. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72670. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72671. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72672. _this._standingMatrix = null;
  72673. // Represents device position and rotation in babylon space
  72674. _this.devicePosition = BABYLON.Vector3.Zero();
  72675. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72676. _this.deviceScaleFactor = 1;
  72677. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72678. _this._worldToDevice = BABYLON.Matrix.Identity();
  72679. _this.controllers = [];
  72680. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72681. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72682. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72683. _this._defaultHeight = 0;
  72684. _this.deviceDistanceToRoomGround = function () {
  72685. if (_this._standingMatrix) {
  72686. // Add standing matrix offset to get real offset from ground in room
  72687. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72688. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72689. }
  72690. else {
  72691. return _this._defaultHeight;
  72692. }
  72693. };
  72694. _this.useStandingMatrix = function (callback) {
  72695. if (callback === void 0) { callback = function (bool) { }; }
  72696. // Use standing matrix if availible
  72697. if (!navigator || !navigator.getVRDisplays) {
  72698. callback(false);
  72699. }
  72700. else {
  72701. navigator.getVRDisplays().then(function (displays) {
  72702. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72703. callback(false);
  72704. }
  72705. else {
  72706. _this._standingMatrix = new BABYLON.Matrix();
  72707. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72708. if (!_this.getScene().useRightHandedSystem) {
  72709. [2, 6, 8, 9, 14].forEach(function (num) {
  72710. if (_this._standingMatrix) {
  72711. _this._standingMatrix.m[num] *= -1;
  72712. }
  72713. });
  72714. }
  72715. callback(true);
  72716. }
  72717. });
  72718. }
  72719. };
  72720. _this._workingVector = BABYLON.Vector3.Zero();
  72721. _this._oneVector = BABYLON.Vector3.One();
  72722. _this._workingMatrix = BABYLON.Matrix.Identity();
  72723. _this._cache.position = BABYLON.Vector3.Zero();
  72724. if (webVROptions.defaultHeight) {
  72725. _this._defaultHeight = webVROptions.defaultHeight;
  72726. _this.position.y = _this._defaultHeight;
  72727. }
  72728. _this.minZ = 0.1;
  72729. //legacy support - the compensation boolean was removed.
  72730. if (arguments.length === 5) {
  72731. _this.webVROptions = arguments[4];
  72732. }
  72733. // default webVR options
  72734. if (_this.webVROptions.trackPosition == undefined) {
  72735. _this.webVROptions.trackPosition = true;
  72736. }
  72737. if (_this.webVROptions.controllerMeshes == undefined) {
  72738. _this.webVROptions.controllerMeshes = true;
  72739. }
  72740. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72741. _this.webVROptions.defaultLightingOnControllers = true;
  72742. }
  72743. _this.rotationQuaternion = new BABYLON.Quaternion();
  72744. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72745. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72746. }
  72747. //enable VR
  72748. var engine = _this.getEngine();
  72749. _this._onVREnabled = function (success) { if (success) {
  72750. _this.initControllers();
  72751. } };
  72752. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72753. engine.initWebVR().add(function (event) {
  72754. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72755. return;
  72756. }
  72757. _this._vrDevice = event.vrDisplay;
  72758. //reset the rig parameters.
  72759. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72760. if (_this._attached) {
  72761. _this.getEngine().enableVR();
  72762. }
  72763. });
  72764. if (typeof (VRFrameData) !== "undefined")
  72765. _this._frameData = new VRFrameData();
  72766. /**
  72767. * The idea behind the following lines:
  72768. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72769. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72770. * the second will not show it correctly.
  72771. *
  72772. * To solve this - each object that has the camera as parent will be added to a protected array.
  72773. * When the rig camera renders, it will take this array and set all of those to be its children.
  72774. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72775. * Amazing!
  72776. */
  72777. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72778. if (camera.parent === _this && _this.rigParenting) {
  72779. _this._descendants = _this.getDescendants(true, function (n) {
  72780. // don't take the cameras or the controllers!
  72781. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72782. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72783. return !isController && !isRigCamera;
  72784. });
  72785. _this._descendants.forEach(function (node) {
  72786. node.parent = camera;
  72787. });
  72788. }
  72789. });
  72790. scene.onAfterCameraRenderObservable.add(function (camera) {
  72791. if (camera.parent === _this && _this.rigParenting) {
  72792. _this._descendants.forEach(function (node) {
  72793. node.parent = _this;
  72794. });
  72795. }
  72796. });
  72797. return _this;
  72798. }
  72799. WebVRFreeCamera.prototype.dispose = function () {
  72800. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72801. _super.prototype.dispose.call(this);
  72802. };
  72803. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72804. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72805. var gp = _a[_i];
  72806. if (gp.hand === name) {
  72807. return gp;
  72808. }
  72809. }
  72810. return null;
  72811. };
  72812. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72813. get: function () {
  72814. if (!this._leftController) {
  72815. this._leftController = this.getControllerByName("left");
  72816. }
  72817. return this._leftController;
  72818. },
  72819. enumerable: true,
  72820. configurable: true
  72821. });
  72822. ;
  72823. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72824. get: function () {
  72825. if (!this._rightController) {
  72826. this._rightController = this.getControllerByName("right");
  72827. }
  72828. return this._rightController;
  72829. },
  72830. enumerable: true,
  72831. configurable: true
  72832. });
  72833. ;
  72834. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72835. if (length === void 0) { length = 100; }
  72836. if (this.leftCamera) {
  72837. // Use left eye to avoid computation to compute center on every call
  72838. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72839. }
  72840. else {
  72841. return _super.prototype.getForwardRay.call(this, length);
  72842. }
  72843. };
  72844. WebVRFreeCamera.prototype._checkInputs = function () {
  72845. if (this._vrDevice && this._vrDevice.isPresenting) {
  72846. this._vrDevice.getFrameData(this._frameData);
  72847. this.updateFromDevice(this._frameData.pose);
  72848. }
  72849. _super.prototype._checkInputs.call(this);
  72850. };
  72851. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72852. if (poseData && poseData.orientation) {
  72853. this.rawPose = poseData;
  72854. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72855. if (this.getScene().useRightHandedSystem) {
  72856. this._deviceRoomRotationQuaternion.z *= -1;
  72857. this._deviceRoomRotationQuaternion.w *= -1;
  72858. }
  72859. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72860. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72861. if (this.getScene().useRightHandedSystem) {
  72862. this._deviceRoomPosition.z *= -1;
  72863. }
  72864. }
  72865. }
  72866. };
  72867. /**
  72868. * WebVR's attach control will start broadcasting frames to the device.
  72869. * Note that in certain browsers (chrome for example) this function must be called
  72870. * within a user-interaction callback. Example:
  72871. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72872. *
  72873. * @param {HTMLElement} element
  72874. * @param {boolean} [noPreventDefault]
  72875. *
  72876. * @memberOf WebVRFreeCamera
  72877. */
  72878. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72879. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72880. this._attached = true;
  72881. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72882. if (this._vrDevice) {
  72883. this.getEngine().enableVR();
  72884. }
  72885. };
  72886. WebVRFreeCamera.prototype.detachControl = function (element) {
  72887. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72888. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72889. _super.prototype.detachControl.call(this, element);
  72890. this._attached = false;
  72891. this.getEngine().disableVR();
  72892. };
  72893. WebVRFreeCamera.prototype.getClassName = function () {
  72894. return "WebVRFreeCamera";
  72895. };
  72896. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72897. //uses the vrDisplay's "resetPose()".
  72898. //pitch and roll won't be affected.
  72899. this._vrDevice.resetPose();
  72900. };
  72901. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72902. var camLeft = this._rigCameras[0];
  72903. var camRight = this._rigCameras[1];
  72904. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72905. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72906. camLeft.position.copyFrom(this._deviceRoomPosition);
  72907. camRight.position.copyFrom(this._deviceRoomPosition);
  72908. };
  72909. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72910. var _this = this;
  72911. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72912. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72913. if (!this.updateCacheCalled) {
  72914. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72915. this.updateCacheCalled = true;
  72916. this.update();
  72917. }
  72918. // Set working vector to the device position in room space rotated by the new rotation
  72919. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72920. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72921. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72922. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72923. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72924. // Add translation from anchor position
  72925. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72926. this._workingVector.addInPlace(this.position);
  72927. this._workingVector.subtractInPlace(this._cache.position);
  72928. this._deviceToWorld.setTranslation(this._workingVector);
  72929. // Set an inverted matrix to be used when updating the camera
  72930. this._deviceToWorld.invertToRef(this._worldToDevice);
  72931. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72932. this.controllers.forEach(function (controller) {
  72933. controller._deviceToWorld = _this._deviceToWorld;
  72934. controller.update();
  72935. });
  72936. }
  72937. if (!ignoreParentClass) {
  72938. _super.prototype._updateCache.call(this);
  72939. }
  72940. this.updateCacheCalled = false;
  72941. };
  72942. WebVRFreeCamera.prototype.update = function () {
  72943. // Get current device position in babylon world
  72944. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72945. // Get current device rotation in babylon world
  72946. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72947. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72948. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72949. _super.prototype.update.call(this);
  72950. };
  72951. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72952. return BABYLON.Matrix.Identity();
  72953. };
  72954. /**
  72955. * This function is called by the two RIG cameras.
  72956. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72957. */
  72958. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72959. var _this = this;
  72960. //WebVR 1.1
  72961. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72962. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72963. if (!this.getScene().useRightHandedSystem) {
  72964. [2, 6, 8, 9, 14].forEach(function (num) {
  72965. _this._webvrViewMatrix.m[num] *= -1;
  72966. });
  72967. }
  72968. // update the camera rotation matrix
  72969. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72970. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72971. // Computing target and final matrix
  72972. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72973. var parentCamera = this._cameraRigParams["parentCamera"];
  72974. // should the view matrix be updated with scale and position offset?
  72975. if (parentCamera.deviceScaleFactor !== 1) {
  72976. this._webvrViewMatrix.invert();
  72977. // scale the position, if set
  72978. if (parentCamera.deviceScaleFactor) {
  72979. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72980. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72981. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72982. }
  72983. this._webvrViewMatrix.invert();
  72984. }
  72985. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72986. return this._webvrViewMatrix;
  72987. };
  72988. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72989. var _this = this;
  72990. var parentCamera = this.parent;
  72991. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72992. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72993. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72994. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72995. //babylon compatible matrix
  72996. if (!this.getScene().useRightHandedSystem) {
  72997. [8, 9, 10, 11].forEach(function (num) {
  72998. _this._projectionMatrix.m[num] *= -1;
  72999. });
  73000. }
  73001. return this._projectionMatrix;
  73002. };
  73003. WebVRFreeCamera.prototype.initControllers = function () {
  73004. var _this = this;
  73005. this.controllers = [];
  73006. var manager = this.getScene().gamepadManager;
  73007. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73008. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  73009. var webVrController = gamepad;
  73010. if (webVrController.defaultModel) {
  73011. webVrController.defaultModel.setEnabled(false);
  73012. }
  73013. if (webVrController.hand === "right") {
  73014. _this._rightController = null;
  73015. }
  73016. if (webVrController.hand === "left") {
  73017. _this._rightController = null;
  73018. }
  73019. var controllerIndex = _this.controllers.indexOf(webVrController);
  73020. if (controllerIndex !== -1) {
  73021. _this.controllers.splice(controllerIndex, 1);
  73022. }
  73023. }
  73024. });
  73025. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73026. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  73027. var webVrController_1 = gamepad;
  73028. webVrController_1._deviceToWorld = _this._deviceToWorld;
  73029. if (_this.webVROptions.controllerMeshes) {
  73030. if (webVrController_1.defaultModel) {
  73031. webVrController_1.defaultModel.setEnabled(true);
  73032. }
  73033. else {
  73034. // Load the meshes
  73035. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  73036. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  73037. if (_this.webVROptions.defaultLightingOnControllers) {
  73038. if (!_this._lightOnControllers) {
  73039. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  73040. }
  73041. var activateLightOnSubMeshes_1 = function (mesh, light) {
  73042. var children = mesh.getChildren();
  73043. if (children.length !== 0) {
  73044. children.forEach(function (mesh) {
  73045. light.includedOnlyMeshes.push(mesh);
  73046. activateLightOnSubMeshes_1(mesh, light);
  73047. });
  73048. }
  73049. };
  73050. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  73051. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  73052. }
  73053. });
  73054. }
  73055. }
  73056. webVrController_1.attachToPoseControlledCamera(_this);
  73057. // since this is async - sanity check. Is the controller already stored?
  73058. if (_this.controllers.indexOf(webVrController_1) === -1) {
  73059. //add to the controllers array
  73060. _this.controllers.push(webVrController_1);
  73061. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  73062. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  73063. // So we're overriding setting left & right manually to be sure
  73064. var firstViveWandDetected = false;
  73065. for (var i = 0; i < _this.controllers.length; i++) {
  73066. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73067. if (!firstViveWandDetected) {
  73068. firstViveWandDetected = true;
  73069. _this.controllers[i].hand = "left";
  73070. }
  73071. else {
  73072. _this.controllers[i].hand = "right";
  73073. }
  73074. }
  73075. }
  73076. //did we find enough controllers? Great! let the developer know.
  73077. if (_this.controllers.length >= 2) {
  73078. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  73079. }
  73080. }
  73081. }
  73082. });
  73083. };
  73084. return WebVRFreeCamera;
  73085. }(BABYLON.FreeCamera));
  73086. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  73087. })(BABYLON || (BABYLON = {}));
  73088. //# sourceMappingURL=babylon.webVRCamera.js.map
  73089. var BABYLON;
  73090. (function (BABYLON) {
  73091. // We're mainly based on the logic defined into the FreeCamera code
  73092. var DeviceOrientationCamera = /** @class */ (function (_super) {
  73093. __extends(DeviceOrientationCamera, _super);
  73094. function DeviceOrientationCamera(name, position, scene) {
  73095. var _this = _super.call(this, name, position, scene) || this;
  73096. _this._quaternionCache = new BABYLON.Quaternion();
  73097. _this.inputs.addDeviceOrientation();
  73098. return _this;
  73099. }
  73100. DeviceOrientationCamera.prototype.getClassName = function () {
  73101. return "DeviceOrientationCamera";
  73102. };
  73103. DeviceOrientationCamera.prototype._checkInputs = function () {
  73104. _super.prototype._checkInputs.call(this);
  73105. this._quaternionCache.copyFrom(this.rotationQuaternion);
  73106. if (this._initialQuaternion) {
  73107. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  73108. }
  73109. };
  73110. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  73111. var _this = this;
  73112. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  73113. //can only work if this camera has a rotation quaternion already.
  73114. if (!this.rotationQuaternion)
  73115. return;
  73116. if (!this._initialQuaternion) {
  73117. this._initialQuaternion = new BABYLON.Quaternion();
  73118. }
  73119. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  73120. ['x', 'y', 'z'].forEach(function (axisName) {
  73121. if (!axis[axisName]) {
  73122. _this._initialQuaternion[axisName] = 0;
  73123. }
  73124. else {
  73125. _this._initialQuaternion[axisName] *= -1;
  73126. }
  73127. });
  73128. this._initialQuaternion.normalize();
  73129. //force rotation update
  73130. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  73131. };
  73132. return DeviceOrientationCamera;
  73133. }(BABYLON.FreeCamera));
  73134. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  73135. })(BABYLON || (BABYLON = {}));
  73136. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  73137. var BABYLON;
  73138. (function (BABYLON) {
  73139. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  73140. __extends(VRDeviceOrientationFreeCamera, _super);
  73141. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  73142. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73143. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73144. var _this = _super.call(this, name, position, scene) || this;
  73145. vrCameraMetrics.compensateDistortion = compensateDistortion;
  73146. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  73147. return _this;
  73148. }
  73149. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  73150. return "VRDeviceOrientationFreeCamera";
  73151. };
  73152. return VRDeviceOrientationFreeCamera;
  73153. }(BABYLON.DeviceOrientationCamera));
  73154. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  73155. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  73156. __extends(VRDeviceOrientationGamepadCamera, _super);
  73157. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  73158. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73159. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73160. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  73161. _this.inputs.addGamepad();
  73162. return _this;
  73163. }
  73164. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  73165. return "VRDeviceOrientationGamepadCamera";
  73166. };
  73167. return VRDeviceOrientationGamepadCamera;
  73168. }(VRDeviceOrientationFreeCamera));
  73169. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  73170. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  73171. __extends(VRDeviceOrientationArcRotateCamera, _super);
  73172. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  73173. if (compensateDistortion === void 0) { compensateDistortion = true; }
  73174. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  73175. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73176. vrCameraMetrics.compensateDistortion = compensateDistortion;
  73177. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  73178. _this.inputs.addVRDeviceOrientation();
  73179. return _this;
  73180. }
  73181. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  73182. return "VRDeviceOrientationArcRotateCamera";
  73183. };
  73184. return VRDeviceOrientationArcRotateCamera;
  73185. }(BABYLON.ArcRotateCamera));
  73186. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  73187. })(BABYLON || (BABYLON = {}));
  73188. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  73189. var BABYLON;
  73190. (function (BABYLON) {
  73191. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  73192. __extends(AnaglyphFreeCamera, _super);
  73193. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  73194. var _this = _super.call(this, name, position, scene) || this;
  73195. _this.interaxialDistance = interaxialDistance;
  73196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73197. return _this;
  73198. }
  73199. AnaglyphFreeCamera.prototype.getClassName = function () {
  73200. return "AnaglyphFreeCamera";
  73201. };
  73202. return AnaglyphFreeCamera;
  73203. }(BABYLON.FreeCamera));
  73204. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  73205. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  73206. __extends(AnaglyphArcRotateCamera, _super);
  73207. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  73208. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73209. _this.interaxialDistance = interaxialDistance;
  73210. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73211. return _this;
  73212. }
  73213. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  73214. return "AnaglyphArcRotateCamera";
  73215. };
  73216. return AnaglyphArcRotateCamera;
  73217. }(BABYLON.ArcRotateCamera));
  73218. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  73219. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  73220. __extends(AnaglyphGamepadCamera, _super);
  73221. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  73222. var _this = _super.call(this, name, position, scene) || this;
  73223. _this.interaxialDistance = interaxialDistance;
  73224. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73225. return _this;
  73226. }
  73227. AnaglyphGamepadCamera.prototype.getClassName = function () {
  73228. return "AnaglyphGamepadCamera";
  73229. };
  73230. return AnaglyphGamepadCamera;
  73231. }(BABYLON.GamepadCamera));
  73232. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  73233. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  73234. __extends(AnaglyphUniversalCamera, _super);
  73235. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73236. var _this = _super.call(this, name, position, scene) || this;
  73237. _this.interaxialDistance = interaxialDistance;
  73238. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73239. return _this;
  73240. }
  73241. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73242. return "AnaglyphUniversalCamera";
  73243. };
  73244. return AnaglyphUniversalCamera;
  73245. }(BABYLON.UniversalCamera));
  73246. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73247. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73248. __extends(StereoscopicFreeCamera, _super);
  73249. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73250. var _this = _super.call(this, name, position, scene) || this;
  73251. _this.interaxialDistance = interaxialDistance;
  73252. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73253. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73254. return _this;
  73255. }
  73256. StereoscopicFreeCamera.prototype.getClassName = function () {
  73257. return "StereoscopicFreeCamera";
  73258. };
  73259. return StereoscopicFreeCamera;
  73260. }(BABYLON.FreeCamera));
  73261. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73262. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73263. __extends(StereoscopicArcRotateCamera, _super);
  73264. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73265. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73266. _this.interaxialDistance = interaxialDistance;
  73267. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73268. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73269. return _this;
  73270. }
  73271. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73272. return "StereoscopicArcRotateCamera";
  73273. };
  73274. return StereoscopicArcRotateCamera;
  73275. }(BABYLON.ArcRotateCamera));
  73276. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73277. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73278. __extends(StereoscopicGamepadCamera, _super);
  73279. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73280. var _this = _super.call(this, name, position, scene) || this;
  73281. _this.interaxialDistance = interaxialDistance;
  73282. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73283. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73284. return _this;
  73285. }
  73286. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73287. return "StereoscopicGamepadCamera";
  73288. };
  73289. return StereoscopicGamepadCamera;
  73290. }(BABYLON.GamepadCamera));
  73291. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73292. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73293. __extends(StereoscopicUniversalCamera, _super);
  73294. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73295. var _this = _super.call(this, name, position, scene) || this;
  73296. _this.interaxialDistance = interaxialDistance;
  73297. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73298. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73299. return _this;
  73300. }
  73301. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73302. return "StereoscopicUniversalCamera";
  73303. };
  73304. return StereoscopicUniversalCamera;
  73305. }(BABYLON.UniversalCamera));
  73306. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73307. })(BABYLON || (BABYLON = {}));
  73308. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73309. var BABYLON;
  73310. (function (BABYLON) {
  73311. var VRExperienceHelper = /** @class */ (function () {
  73312. function VRExperienceHelper(scene, webVROptions) {
  73313. if (webVROptions === void 0) { webVROptions = {}; }
  73314. var _this = this;
  73315. this.webVROptions = webVROptions;
  73316. // Can the system support WebVR, even if a headset isn't plugged in?
  73317. this._webVRsupported = false;
  73318. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73319. this._webVRready = false;
  73320. // Are we waiting for the requestPresent callback to complete?
  73321. this._webVRrequesting = false;
  73322. // Are we presenting to the headset right now?
  73323. this._webVRpresenting = false;
  73324. // Are we presenting in the fullscreen fallback?
  73325. this._fullscreenVRpresenting = false;
  73326. /**
  73327. * Observable raised when entering VR.
  73328. */
  73329. this.onEnteringVRObservable = new BABYLON.Observable();
  73330. /**
  73331. * Observable raised when exiting VR.
  73332. */
  73333. this.onExitingVRObservable = new BABYLON.Observable();
  73334. /**
  73335. * Observable raised when controller mesh is loaded.
  73336. */
  73337. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73338. this._useCustomVRButton = false;
  73339. this._teleportationRequested = false;
  73340. this._teleportationEnabledOnLeftController = false;
  73341. this._teleportationEnabledOnRightController = false;
  73342. this._interactionsEnabledOnLeftController = false;
  73343. this._interactionsEnabledOnRightController = false;
  73344. this._leftControllerReady = false;
  73345. this._rightControllerReady = false;
  73346. this._floorMeshesCollection = [];
  73347. this._teleportationAllowed = false;
  73348. this._rotationAllowed = true;
  73349. this._teleportationRequestInitiated = false;
  73350. this._teleportationBackRequestInitiated = false;
  73351. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73352. this._rotationRightAsked = false;
  73353. this._rotationLeftAsked = false;
  73354. this._isDefaultTeleportationTarget = true;
  73355. this._teleportationFillColor = "#444444";
  73356. this._teleportationBorderColor = "#FFFFFF";
  73357. this._rotationAngle = 0;
  73358. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73359. this._padSensibilityUp = 0.65;
  73360. this._padSensibilityDown = 0.35;
  73361. /**
  73362. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73363. */
  73364. this.onNewMeshSelected = new BABYLON.Observable();
  73365. /**
  73366. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73367. */
  73368. this.onNewMeshPicked = new BABYLON.Observable();
  73369. /**
  73370. * Observable raised before camera teleportation
  73371. */
  73372. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73373. /**
  73374. * Observable raised after camera teleportation
  73375. */
  73376. this.onAfterCameraTeleport = new BABYLON.Observable();
  73377. /**
  73378. * Observable raised when current selected mesh gets unselected
  73379. */
  73380. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73381. /**
  73382. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73383. */
  73384. this.teleportationEnabled = true;
  73385. this._pointerDownOnMeshAsked = false;
  73386. this._isActionableMesh = false;
  73387. this._teleportationInitialized = false;
  73388. this._interactionsEnabled = false;
  73389. this._interactionsRequested = false;
  73390. this._displayGaze = true;
  73391. this._displayLaserPointer = true;
  73392. this._dpadPressed = true;
  73393. this._onResize = function () {
  73394. _this.moveButtonToBottomRight();
  73395. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73396. _this.exitVR();
  73397. }
  73398. };
  73399. this._onFullscreenChange = function () {
  73400. if (document.fullscreen !== undefined) {
  73401. _this._fullscreenVRpresenting = document.fullscreen;
  73402. }
  73403. else if (document.mozFullScreen !== undefined) {
  73404. _this._fullscreenVRpresenting = document.mozFullScreen;
  73405. }
  73406. else if (document.webkitIsFullScreen !== undefined) {
  73407. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73408. }
  73409. else if (document.msIsFullScreen !== undefined) {
  73410. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73411. }
  73412. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73413. _this.exitVR();
  73414. if (!_this._useCustomVRButton) {
  73415. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73416. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73417. }
  73418. }
  73419. };
  73420. this.beforeRender = function () {
  73421. _this._castRayAndSelectObject();
  73422. };
  73423. this._onNewGamepadConnected = function (gamepad) {
  73424. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73425. if (gamepad.leftStick) {
  73426. gamepad.onleftstickchanged(function (stickValues) {
  73427. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73428. // Listening to classic/xbox gamepad only if no VR controller is active
  73429. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73430. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73431. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73432. _this._checkTeleportWithRay(stickValues);
  73433. _this._checkTeleportBackwards(stickValues);
  73434. }
  73435. }
  73436. });
  73437. }
  73438. if (gamepad.rightStick) {
  73439. gamepad.onrightstickchanged(function (stickValues) {
  73440. if (_this._teleportationInitialized) {
  73441. _this._checkRotate(stickValues);
  73442. }
  73443. });
  73444. }
  73445. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73446. gamepad.onbuttondown(function (buttonPressed) {
  73447. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73448. _this._selectionPointerDown();
  73449. }
  73450. });
  73451. gamepad.onbuttonup(function (buttonPressed) {
  73452. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73453. _this._selectionPointerUp();
  73454. }
  73455. });
  73456. }
  73457. }
  73458. else {
  73459. var webVRController = gamepad;
  73460. _this._tryEnableInteractionOnController(webVRController);
  73461. }
  73462. };
  73463. // 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
  73464. this._tryEnableInteractionOnController = function (webVRController) {
  73465. if (webVRController.hand === "left") {
  73466. _this._leftControllerReady = true;
  73467. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73468. _this._enableInteractionOnController(webVRController);
  73469. }
  73470. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73471. _this._enableTeleportationOnController(webVRController);
  73472. }
  73473. }
  73474. if (webVRController.hand === "right") {
  73475. _this._rightControllerReady = true;
  73476. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73477. _this._enableInteractionOnController(webVRController);
  73478. }
  73479. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73480. _this._enableTeleportationOnController(webVRController);
  73481. }
  73482. }
  73483. };
  73484. this._onNewGamepadDisconnected = function (gamepad) {
  73485. if (gamepad instanceof BABYLON.WebVRController) {
  73486. if (gamepad.hand === "left") {
  73487. _this._interactionsEnabledOnLeftController = false;
  73488. _this._teleportationEnabledOnLeftController = false;
  73489. _this._leftControllerReady = false;
  73490. if (_this._leftLaserPointer) {
  73491. _this._leftLaserPointer.dispose();
  73492. }
  73493. }
  73494. if (gamepad.hand === "right") {
  73495. _this._interactionsEnabledOnRightController = false;
  73496. _this._teleportationEnabledOnRightController = false;
  73497. _this._rightControllerReady = false;
  73498. if (_this._rightLaserPointer) {
  73499. _this._rightLaserPointer.dispose();
  73500. }
  73501. }
  73502. }
  73503. };
  73504. this._workingVector = BABYLON.Vector3.Zero();
  73505. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73506. this._workingMatrix = BABYLON.Matrix.Identity();
  73507. this._scene = scene;
  73508. this._canvas = scene.getEngine().getRenderingCanvas();
  73509. // Parse options
  73510. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73511. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73512. }
  73513. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73514. webVROptions.createDeviceOrientationCamera = true;
  73515. }
  73516. if (webVROptions.defaultHeight === undefined) {
  73517. webVROptions.defaultHeight = 1.7;
  73518. }
  73519. if (webVROptions.useCustomVRButton) {
  73520. this._useCustomVRButton = true;
  73521. if (webVROptions.customVRButton) {
  73522. this._btnVR = webVROptions.customVRButton;
  73523. }
  73524. }
  73525. if (webVROptions.rayLength) {
  73526. this._rayLength = webVROptions.rayLength;
  73527. }
  73528. this._defaultHeight = webVROptions.defaultHeight;
  73529. // Set position
  73530. if (this._scene.activeCamera) {
  73531. this._position = this._scene.activeCamera.position.clone();
  73532. }
  73533. else {
  73534. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73535. }
  73536. // Set non-vr camera
  73537. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73538. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73539. // Copy data from existing camera
  73540. if (this._scene.activeCamera) {
  73541. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73542. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73543. // Set rotation from previous camera
  73544. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73545. var targetCamera = this._scene.activeCamera;
  73546. if (targetCamera.rotationQuaternion) {
  73547. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73548. }
  73549. else {
  73550. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73551. }
  73552. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73553. }
  73554. }
  73555. this._scene.activeCamera = this._deviceOrientationCamera;
  73556. if (this._canvas) {
  73557. this._scene.activeCamera.attachControl(this._canvas);
  73558. }
  73559. }
  73560. else {
  73561. this._existingCamera = this._scene.activeCamera;
  73562. }
  73563. // Create VR cameras
  73564. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73565. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73566. }
  73567. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73568. this._webVRCamera.useStandingMatrix();
  73569. // Create default button
  73570. if (!this._useCustomVRButton) {
  73571. this._btnVR = document.createElement("BUTTON");
  73572. this._btnVR.className = "babylonVRicon";
  73573. this._btnVR.id = "babylonVRiconbtn";
  73574. this._btnVR.title = "Click to switch to VR";
  73575. 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) }";
  73576. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73577. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73578. // css += ".babylonVRicon.vrdisplaysupported { }";
  73579. // css += ".babylonVRicon.vrdisplayready { }";
  73580. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73581. var style = document.createElement('style');
  73582. style.appendChild(document.createTextNode(css));
  73583. document.getElementsByTagName('head')[0].appendChild(style);
  73584. this.moveButtonToBottomRight();
  73585. }
  73586. // VR button click event
  73587. if (this._btnVR) {
  73588. this._btnVR.addEventListener("click", function () {
  73589. if (!_this.isInVRMode) {
  73590. _this.enterVR();
  73591. }
  73592. else {
  73593. _this.exitVR();
  73594. }
  73595. });
  73596. }
  73597. // Window events
  73598. window.addEventListener("resize", this._onResize);
  73599. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73600. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73601. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73602. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73603. // Display vr button when headset is connected
  73604. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73605. this.displayVRButton();
  73606. }
  73607. else {
  73608. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73609. if (e.vrDisplay) {
  73610. _this.displayVRButton();
  73611. }
  73612. });
  73613. }
  73614. // Exiting VR mode using 'ESC' key on desktop
  73615. this._onKeyDown = function (event) {
  73616. if (event.keyCode === 27 && _this.isInVRMode) {
  73617. _this.exitVR();
  73618. }
  73619. };
  73620. document.addEventListener("keydown", this._onKeyDown);
  73621. // Exiting VR mode double tapping the touch screen
  73622. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73623. if (_this.isInVRMode) {
  73624. _this.exitVR();
  73625. if (_this._fullscreenVRpresenting) {
  73626. _this._scene.getEngine().switchFullscreen(true);
  73627. }
  73628. }
  73629. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73630. // Listen for WebVR display changes
  73631. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73632. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73633. this._onVRRequestPresentStart = function () {
  73634. _this._webVRrequesting = true;
  73635. _this.updateButtonVisibility();
  73636. };
  73637. this._onVRRequestPresentComplete = function (success) {
  73638. _this._webVRrequesting = false;
  73639. _this.updateButtonVisibility();
  73640. };
  73641. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73642. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73643. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73644. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73645. scene.onDisposeObservable.add(function () {
  73646. _this.dispose();
  73647. });
  73648. // Gamepad connection events
  73649. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73650. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73651. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73652. this.updateButtonVisibility();
  73653. //create easing functions
  73654. this._circleEase = new BABYLON.CircleEase();
  73655. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73656. }
  73657. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73658. /** Return this.onEnteringVRObservable
  73659. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73660. */
  73661. get: function () {
  73662. return this.onEnteringVRObservable;
  73663. },
  73664. enumerable: true,
  73665. configurable: true
  73666. });
  73667. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73668. /** Return this.onExitingVRObservable
  73669. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73670. */
  73671. get: function () {
  73672. return this.onExitingVRObservable;
  73673. },
  73674. enumerable: true,
  73675. configurable: true
  73676. });
  73677. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73678. /** Return this.onControllerMeshLoadedObservable
  73679. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73680. */
  73681. get: function () {
  73682. return this.onControllerMeshLoadedObservable;
  73683. },
  73684. enumerable: true,
  73685. configurable: true
  73686. });
  73687. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73688. get: function () {
  73689. return this._teleportationTarget;
  73690. },
  73691. set: function (value) {
  73692. if (value) {
  73693. value.name = "teleportationTarget";
  73694. this._isDefaultTeleportationTarget = false;
  73695. this._teleportationTarget = value;
  73696. }
  73697. },
  73698. enumerable: true,
  73699. configurable: true
  73700. });
  73701. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73702. get: function () {
  73703. return this._displayGaze;
  73704. },
  73705. set: function (value) {
  73706. this._displayGaze = value;
  73707. if (!value) {
  73708. this._gazeTracker.isVisible = false;
  73709. }
  73710. },
  73711. enumerable: true,
  73712. configurable: true
  73713. });
  73714. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73715. get: function () {
  73716. return this._displayLaserPointer;
  73717. },
  73718. set: function (value) {
  73719. this._displayLaserPointer = value;
  73720. if (!value) {
  73721. if (this._rightLaserPointer) {
  73722. this._rightLaserPointer.isVisible = false;
  73723. }
  73724. if (this._leftLaserPointer) {
  73725. this._leftLaserPointer.isVisible = false;
  73726. }
  73727. }
  73728. else {
  73729. if (this._rightLaserPointer) {
  73730. this._rightLaserPointer.isVisible = true;
  73731. }
  73732. else if (this._leftLaserPointer) {
  73733. this._leftLaserPointer.isVisible = true;
  73734. }
  73735. }
  73736. },
  73737. enumerable: true,
  73738. configurable: true
  73739. });
  73740. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73741. get: function () {
  73742. return this._deviceOrientationCamera;
  73743. },
  73744. enumerable: true,
  73745. configurable: true
  73746. });
  73747. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73748. // Based on the current WebVR support, returns the current VR camera used
  73749. get: function () {
  73750. if (this._webVRready) {
  73751. return this._webVRCamera;
  73752. }
  73753. else {
  73754. return this._scene.activeCamera;
  73755. }
  73756. },
  73757. enumerable: true,
  73758. configurable: true
  73759. });
  73760. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73761. get: function () {
  73762. return this._webVRCamera;
  73763. },
  73764. enumerable: true,
  73765. configurable: true
  73766. });
  73767. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73768. get: function () {
  73769. return this._vrDeviceOrientationCamera;
  73770. },
  73771. enumerable: true,
  73772. configurable: true
  73773. });
  73774. // Raised when one of the controller has loaded successfully its associated default mesh
  73775. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73776. this._tryEnableInteractionOnController(webVRController);
  73777. try {
  73778. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73779. }
  73780. catch (err) {
  73781. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73782. }
  73783. };
  73784. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73785. /**
  73786. * Gets a value indicating if we are currently in VR mode.
  73787. */
  73788. get: function () {
  73789. return this._webVRpresenting || this._fullscreenVRpresenting;
  73790. },
  73791. enumerable: true,
  73792. configurable: true
  73793. });
  73794. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73795. var vrDisplay = this._scene.getEngine().getVRDevice();
  73796. if (vrDisplay) {
  73797. var wasPresenting = this._webVRpresenting;
  73798. // A VR display is connected
  73799. this._webVRpresenting = vrDisplay.isPresenting;
  73800. if (wasPresenting && !this._webVRpresenting)
  73801. this.exitVR();
  73802. }
  73803. else {
  73804. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73805. }
  73806. this.updateButtonVisibility();
  73807. };
  73808. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73809. this._webVRsupported = eventArgs.vrSupported;
  73810. this._webVRready = !!eventArgs.vrDisplay;
  73811. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73812. this.updateButtonVisibility();
  73813. };
  73814. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73815. if (this._canvas && !this._useCustomVRButton) {
  73816. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73817. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73818. }
  73819. };
  73820. VRExperienceHelper.prototype.displayVRButton = function () {
  73821. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73822. document.body.appendChild(this._btnVR);
  73823. this._btnVRDisplayed = true;
  73824. }
  73825. };
  73826. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73827. if (!this._btnVR || this._useCustomVRButton) {
  73828. return;
  73829. }
  73830. this._btnVR.className = "babylonVRicon";
  73831. if (this.isInVRMode) {
  73832. this._btnVR.className += " vrdisplaypresenting";
  73833. }
  73834. else {
  73835. if (this._webVRready)
  73836. this._btnVR.className += " vrdisplayready";
  73837. if (this._webVRsupported)
  73838. this._btnVR.className += " vrdisplaysupported";
  73839. if (this._webVRrequesting)
  73840. this._btnVR.className += " vrdisplayrequesting";
  73841. }
  73842. };
  73843. /**
  73844. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73845. * Otherwise, will use the fullscreen API.
  73846. */
  73847. VRExperienceHelper.prototype.enterVR = function () {
  73848. if (this.onEnteringVRObservable) {
  73849. try {
  73850. this.onEnteringVRObservable.notifyObservers(this);
  73851. }
  73852. catch (err) {
  73853. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73854. }
  73855. }
  73856. if (this._scene.activeCamera) {
  73857. this._position = this._scene.activeCamera.position.clone();
  73858. // make sure that we return to the last active camera
  73859. this._existingCamera = this._scene.activeCamera;
  73860. }
  73861. if (this._webVRrequesting)
  73862. return;
  73863. // If WebVR is supported and a headset is connected
  73864. if (this._webVRready) {
  73865. if (!this._webVRpresenting) {
  73866. this._webVRCamera.position = this._position;
  73867. this._scene.activeCamera = this._webVRCamera;
  73868. }
  73869. }
  73870. else if (this._vrDeviceOrientationCamera) {
  73871. this._vrDeviceOrientationCamera.position = this._position;
  73872. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73873. this._scene.getEngine().switchFullscreen(true);
  73874. this.updateButtonVisibility();
  73875. }
  73876. if (this._scene.activeCamera && this._canvas) {
  73877. this._scene.activeCamera.attachControl(this._canvas);
  73878. }
  73879. if (this._interactionsEnabled) {
  73880. this._scene.registerBeforeRender(this.beforeRender);
  73881. }
  73882. };
  73883. /**
  73884. * Attempt to exit VR, or fullscreen.
  73885. */
  73886. VRExperienceHelper.prototype.exitVR = function () {
  73887. if (this.onExitingVRObservable) {
  73888. try {
  73889. this.onExitingVRObservable.notifyObservers(this);
  73890. }
  73891. catch (err) {
  73892. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73893. }
  73894. }
  73895. if (this._webVRpresenting) {
  73896. this._scene.getEngine().disableVR();
  73897. }
  73898. if (this._scene.activeCamera) {
  73899. this._position = this._scene.activeCamera.position.clone();
  73900. }
  73901. if (this._deviceOrientationCamera) {
  73902. this._deviceOrientationCamera.position = this._position;
  73903. this._scene.activeCamera = this._deviceOrientationCamera;
  73904. if (this._canvas) {
  73905. this._scene.activeCamera.attachControl(this._canvas);
  73906. }
  73907. }
  73908. else if (this._existingCamera) {
  73909. this._existingCamera.position = this._position;
  73910. this._scene.activeCamera = this._existingCamera;
  73911. }
  73912. this.updateButtonVisibility();
  73913. if (this._interactionsEnabled) {
  73914. this._scene.unregisterBeforeRender(this.beforeRender);
  73915. }
  73916. };
  73917. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73918. get: function () {
  73919. return this._position;
  73920. },
  73921. set: function (value) {
  73922. this._position = value;
  73923. if (this._scene.activeCamera) {
  73924. this._scene.activeCamera.position = value;
  73925. }
  73926. },
  73927. enumerable: true,
  73928. configurable: true
  73929. });
  73930. VRExperienceHelper.prototype.enableInteractions = function () {
  73931. var _this = this;
  73932. if (!this._interactionsEnabled) {
  73933. this._interactionsRequested = true;
  73934. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73935. this._enableInteractionOnController(this._webVRCamera.leftController);
  73936. }
  73937. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73938. this._enableInteractionOnController(this._webVRCamera.rightController);
  73939. }
  73940. this._createGazeTracker();
  73941. this.raySelectionPredicate = function (mesh) {
  73942. return mesh.isVisible;
  73943. };
  73944. this.meshSelectionPredicate = function (mesh) {
  73945. return true;
  73946. };
  73947. this._raySelectionPredicate = function (mesh) {
  73948. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73949. && mesh.name.indexOf("teleportationTarget") === -1
  73950. && mesh.name.indexOf("torusTeleportation") === -1
  73951. && mesh.name.indexOf("laserPointer") === -1)) {
  73952. return _this.raySelectionPredicate(mesh);
  73953. }
  73954. return false;
  73955. };
  73956. this._interactionsEnabled = true;
  73957. }
  73958. };
  73959. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73960. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73961. if (this._floorMeshesCollection[i].id === mesh.id) {
  73962. return true;
  73963. }
  73964. }
  73965. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73966. return true;
  73967. }
  73968. return false;
  73969. };
  73970. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73971. if (!this._floorMeshesCollection) {
  73972. return;
  73973. }
  73974. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73975. return;
  73976. }
  73977. this._floorMeshesCollection.push(floorMesh);
  73978. };
  73979. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73980. if (!this._floorMeshesCollection) {
  73981. return;
  73982. }
  73983. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73984. if (meshIndex !== -1) {
  73985. this._floorMeshesCollection.splice(meshIndex, 1);
  73986. }
  73987. };
  73988. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73989. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73990. if (!this._teleportationInitialized) {
  73991. this._teleportationRequested = true;
  73992. this.enableInteractions();
  73993. if (vrTeleportationOptions.floorMeshName) {
  73994. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73995. }
  73996. if (vrTeleportationOptions.floorMeshes) {
  73997. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73998. }
  73999. if (this._leftControllerReady && this._webVRCamera.leftController) {
  74000. this._enableTeleportationOnController(this._webVRCamera.leftController);
  74001. }
  74002. if (this._rightControllerReady && this._webVRCamera.rightController) {
  74003. this._enableTeleportationOnController(this._webVRCamera.rightController);
  74004. }
  74005. // Creates an image processing post process for the vignette not relying
  74006. // on the main scene configuration for image processing to reduce setup and spaces
  74007. // (gamma/linear) conflicts.
  74008. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  74009. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  74010. imageProcessingConfiguration.vignetteEnabled = true;
  74011. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  74012. this._webVRCamera.detachPostProcess(this._postProcessMove);
  74013. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  74014. this._teleportationInitialized = true;
  74015. if (this._isDefaultTeleportationTarget) {
  74016. this._createTeleportationCircles();
  74017. }
  74018. }
  74019. };
  74020. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  74021. var _this = this;
  74022. var controllerMesh = webVRController.mesh;
  74023. if (controllerMesh) {
  74024. var makeNotPick = function (root) {
  74025. root.name += " laserPointer";
  74026. root.getChildMeshes().forEach(function (c) {
  74027. makeNotPick(c);
  74028. });
  74029. };
  74030. makeNotPick(controllerMesh);
  74031. var childMeshes = controllerMesh.getChildMeshes();
  74032. for (var i = 0; i < childMeshes.length; i++) {
  74033. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  74034. controllerMesh = childMeshes[i];
  74035. break;
  74036. }
  74037. }
  74038. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  74039. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  74040. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74041. laserPointerMaterial.alpha = 0.6;
  74042. laserPointer.material = laserPointerMaterial;
  74043. laserPointer.rotation.x = Math.PI / 2;
  74044. laserPointer.parent = controllerMesh;
  74045. laserPointer.position.z = -0.5;
  74046. laserPointer.isVisible = false;
  74047. if (webVRController.hand === "left") {
  74048. this._leftLaserPointer = laserPointer;
  74049. this._interactionsEnabledOnLeftController = true;
  74050. if (!this._rightLaserPointer) {
  74051. this._leftLaserPointer.isVisible = true;
  74052. }
  74053. }
  74054. else {
  74055. this._rightLaserPointer = laserPointer;
  74056. this._interactionsEnabledOnRightController = true;
  74057. if (!this._leftLaserPointer) {
  74058. this._rightLaserPointer.isVisible = true;
  74059. }
  74060. }
  74061. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  74062. // Enabling / disabling laserPointer
  74063. if (_this._displayLaserPointer && stateObject.value === 1) {
  74064. laserPointer.isVisible = !laserPointer.isVisible;
  74065. // Laser pointer can only be active on left or right, not both at the same time
  74066. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  74067. _this._rightLaserPointer.isVisible = false;
  74068. }
  74069. else if (_this._leftLaserPointer) {
  74070. _this._leftLaserPointer.isVisible = false;
  74071. }
  74072. }
  74073. });
  74074. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  74075. if (!_this._pointerDownOnMeshAsked) {
  74076. if (stateObject.value > _this._padSensibilityUp) {
  74077. _this._selectionPointerDown();
  74078. }
  74079. }
  74080. else if (stateObject.value < _this._padSensibilityDown) {
  74081. _this._selectionPointerUp();
  74082. }
  74083. });
  74084. }
  74085. };
  74086. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  74087. if (webVRController === void 0) { webVRController = null; }
  74088. if (!this._teleportationRequestInitiated) {
  74089. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  74090. if (webVRController) {
  74091. // If laser pointer wasn't enabled yet
  74092. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  74093. this._leftLaserPointer.isVisible = true;
  74094. if (this._rightLaserPointer) {
  74095. this._rightLaserPointer.isVisible = false;
  74096. }
  74097. }
  74098. else if (this._displayLaserPointer && this._rightLaserPointer) {
  74099. this._rightLaserPointer.isVisible = true;
  74100. if (this._leftLaserPointer) {
  74101. this._leftLaserPointer.isVisible = false;
  74102. }
  74103. }
  74104. }
  74105. this._teleportationRequestInitiated = true;
  74106. }
  74107. }
  74108. else {
  74109. // Listening to the proper controller values changes to confirm teleportation
  74110. if (webVRController == null
  74111. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  74112. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  74113. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  74114. if (this._teleportationAllowed) {
  74115. this._teleportationAllowed = false;
  74116. this._teleportCamera();
  74117. }
  74118. this._teleportationRequestInitiated = false;
  74119. }
  74120. }
  74121. }
  74122. };
  74123. VRExperienceHelper.prototype._selectionPointerDown = function () {
  74124. this._pointerDownOnMeshAsked = true;
  74125. if (this._currentMeshSelected && this._currentHit) {
  74126. this._scene.simulatePointerDown(this._currentHit);
  74127. }
  74128. };
  74129. VRExperienceHelper.prototype._selectionPointerUp = function () {
  74130. if (this._currentMeshSelected && this._currentHit) {
  74131. this._scene.simulatePointerUp(this._currentHit);
  74132. }
  74133. this._pointerDownOnMeshAsked = false;
  74134. };
  74135. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  74136. // Only rotate when user is not currently selecting a teleportation location
  74137. if (this._teleportationRequestInitiated) {
  74138. return;
  74139. }
  74140. if (!this._rotationLeftAsked) {
  74141. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  74142. this._rotationLeftAsked = true;
  74143. if (this._rotationAllowed) {
  74144. this._rotateCamera(false);
  74145. }
  74146. }
  74147. }
  74148. else {
  74149. if (stateObject.x > -this._padSensibilityDown) {
  74150. this._rotationLeftAsked = false;
  74151. }
  74152. }
  74153. if (!this._rotationRightAsked) {
  74154. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  74155. this._rotationRightAsked = true;
  74156. if (this._rotationAllowed) {
  74157. this._rotateCamera(true);
  74158. }
  74159. }
  74160. }
  74161. else {
  74162. if (stateObject.x < this._padSensibilityDown) {
  74163. this._rotationRightAsked = false;
  74164. }
  74165. }
  74166. };
  74167. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  74168. // Only teleport backwards when user is not currently selecting a teleportation location
  74169. if (this._teleportationRequestInitiated) {
  74170. return;
  74171. }
  74172. // Teleport backwards
  74173. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  74174. if (!this._teleportationBackRequestInitiated) {
  74175. if (!this.currentVRCamera) {
  74176. return;
  74177. }
  74178. // Get rotation and position of the current camera
  74179. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  74180. var position = this.currentVRCamera.position;
  74181. // If the camera has device position, use that instead
  74182. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  74183. rotation = this.currentVRCamera.deviceRotationQuaternion;
  74184. position = this.currentVRCamera.devicePosition;
  74185. }
  74186. // Get matrix with only the y rotation of the device rotation
  74187. rotation.toEulerAnglesToRef(this._workingVector);
  74188. this._workingVector.z = 0;
  74189. this._workingVector.x = 0;
  74190. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  74191. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  74192. // Rotate backwards ray by device rotation to cast at the ground behind the user
  74193. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  74194. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  74195. var ray = new BABYLON.Ray(position, this._workingVector);
  74196. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74197. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  74198. this._teleportCamera(hit.pickedPoint);
  74199. }
  74200. this._teleportationBackRequestInitiated = true;
  74201. }
  74202. }
  74203. else {
  74204. this._teleportationBackRequestInitiated = false;
  74205. }
  74206. };
  74207. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  74208. var _this = this;
  74209. var controllerMesh = webVRController.mesh;
  74210. if (controllerMesh) {
  74211. if (webVRController.hand === "left") {
  74212. if (!this._interactionsEnabledOnLeftController) {
  74213. this._enableInteractionOnController(webVRController);
  74214. }
  74215. this._teleportationEnabledOnLeftController = true;
  74216. }
  74217. else {
  74218. if (!this._interactionsEnabledOnRightController) {
  74219. this._enableInteractionOnController(webVRController);
  74220. }
  74221. this._teleportationEnabledOnRightController = true;
  74222. }
  74223. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74224. this._dpadPressed = false;
  74225. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  74226. _this._dpadPressed = stateObject.pressed;
  74227. if (!_this._dpadPressed) {
  74228. _this._rotationLeftAsked = false;
  74229. _this._rotationRightAsked = false;
  74230. _this._teleportationBackRequestInitiated = false;
  74231. }
  74232. });
  74233. }
  74234. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  74235. if (_this.teleportationEnabled) {
  74236. _this._checkTeleportBackwards(stateObject);
  74237. _this._checkTeleportWithRay(stateObject, webVRController);
  74238. }
  74239. _this._checkRotate(stateObject);
  74240. });
  74241. }
  74242. };
  74243. // Gaze support used to point to teleport or to interact with an object
  74244. VRExperienceHelper.prototype._createGazeTracker = function () {
  74245. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74246. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74247. this._gazeTracker.isPickable = false;
  74248. this._gazeTracker.isVisible = false;
  74249. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74250. targetMat.specularColor = BABYLON.Color3.Black();
  74251. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74252. targetMat.backFaceCulling = false;
  74253. this._gazeTracker.material = targetMat;
  74254. };
  74255. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74256. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74257. this._teleportationTarget.isPickable = false;
  74258. var length = 512;
  74259. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74260. dynamicTexture.hasAlpha = true;
  74261. var context = dynamicTexture.getContext();
  74262. var centerX = length / 2;
  74263. var centerY = length / 2;
  74264. var radius = 200;
  74265. context.beginPath();
  74266. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74267. context.fillStyle = this._teleportationFillColor;
  74268. context.fill();
  74269. context.lineWidth = 10;
  74270. context.strokeStyle = this._teleportationBorderColor;
  74271. context.stroke();
  74272. context.closePath();
  74273. dynamicTexture.update();
  74274. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74275. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74276. this._teleportationTarget.material = teleportationCircleMaterial;
  74277. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74278. torus.isPickable = false;
  74279. torus.parent = this._teleportationTarget;
  74280. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74281. var keys = [];
  74282. keys.push({
  74283. frame: 0,
  74284. value: 0
  74285. });
  74286. keys.push({
  74287. frame: 30,
  74288. value: 0.4
  74289. });
  74290. keys.push({
  74291. frame: 60,
  74292. value: 0
  74293. });
  74294. animationInnerCircle.setKeys(keys);
  74295. var easingFunction = new BABYLON.SineEase();
  74296. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74297. animationInnerCircle.setEasingFunction(easingFunction);
  74298. torus.animations = [];
  74299. torus.animations.push(animationInnerCircle);
  74300. this._scene.beginAnimation(torus, 0, 60, true);
  74301. this._hideTeleportationTarget();
  74302. };
  74303. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74304. if (this._teleportationInitialized) {
  74305. this._teleportationTarget.isVisible = true;
  74306. if (this._isDefaultTeleportationTarget) {
  74307. this._teleportationTarget.getChildren()[0].isVisible = true;
  74308. }
  74309. }
  74310. };
  74311. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74312. if (this._teleportationInitialized) {
  74313. this._teleportationTarget.isVisible = false;
  74314. if (this._isDefaultTeleportationTarget) {
  74315. this._teleportationTarget.getChildren()[0].isVisible = false;
  74316. }
  74317. }
  74318. };
  74319. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74320. var _this = this;
  74321. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74322. return;
  74323. }
  74324. if (right) {
  74325. this._rotationAngle++;
  74326. }
  74327. else {
  74328. this._rotationAngle--;
  74329. }
  74330. this.currentVRCamera.animations = [];
  74331. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74332. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74333. var animationRotationKeys = [];
  74334. animationRotationKeys.push({
  74335. frame: 0,
  74336. value: this.currentVRCamera.rotationQuaternion
  74337. });
  74338. animationRotationKeys.push({
  74339. frame: 6,
  74340. value: target
  74341. });
  74342. animationRotation.setKeys(animationRotationKeys);
  74343. animationRotation.setEasingFunction(this._circleEase);
  74344. this.currentVRCamera.animations.push(animationRotation);
  74345. this._postProcessMove.animations = [];
  74346. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74347. var vignetteWeightKeys = [];
  74348. vignetteWeightKeys.push({
  74349. frame: 0,
  74350. value: 0
  74351. });
  74352. vignetteWeightKeys.push({
  74353. frame: 3,
  74354. value: 4
  74355. });
  74356. vignetteWeightKeys.push({
  74357. frame: 6,
  74358. value: 0
  74359. });
  74360. animationPP.setKeys(vignetteWeightKeys);
  74361. animationPP.setEasingFunction(this._circleEase);
  74362. this._postProcessMove.animations.push(animationPP);
  74363. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74364. var vignetteStretchKeys = [];
  74365. vignetteStretchKeys.push({
  74366. frame: 0,
  74367. value: 0
  74368. });
  74369. vignetteStretchKeys.push({
  74370. frame: 3,
  74371. value: 10
  74372. });
  74373. vignetteStretchKeys.push({
  74374. frame: 6,
  74375. value: 0
  74376. });
  74377. animationPP2.setKeys(vignetteStretchKeys);
  74378. animationPP2.setEasingFunction(this._circleEase);
  74379. this._postProcessMove.animations.push(animationPP2);
  74380. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74381. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74382. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74383. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74384. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74385. });
  74386. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74387. };
  74388. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74389. if (hit.pickedPoint) {
  74390. this._teleportationAllowed = true;
  74391. if (this._teleportationRequestInitiated) {
  74392. this._displayTeleportationTarget();
  74393. }
  74394. else {
  74395. this._hideTeleportationTarget();
  74396. }
  74397. this._haloCenter.copyFrom(hit.pickedPoint);
  74398. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74399. var pickNormal = hit.getNormal(true, false);
  74400. if (pickNormal) {
  74401. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74402. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74403. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74404. }
  74405. this._teleportationTarget.position.y += 0.1;
  74406. }
  74407. };
  74408. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74409. var _this = this;
  74410. if (location === void 0) { location = null; }
  74411. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74412. return;
  74413. }
  74414. if (!location) {
  74415. location = this._haloCenter;
  74416. }
  74417. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74418. // offset of the headset from the anchor.
  74419. if (this.webVRCamera.leftCamera) {
  74420. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74421. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74422. location.subtractToRef(this._workingVector, this._workingVector);
  74423. }
  74424. else {
  74425. this._workingVector.copyFrom(location);
  74426. }
  74427. // Add height to account for user's height offset
  74428. if (this.isInVRMode) {
  74429. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74430. }
  74431. else {
  74432. this._workingVector.y += this._defaultHeight;
  74433. }
  74434. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74435. // Create animation from the camera's position to the new location
  74436. this.currentVRCamera.animations = [];
  74437. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74438. var animationCameraTeleportationKeys = [{
  74439. frame: 0,
  74440. value: this.currentVRCamera.position
  74441. },
  74442. {
  74443. frame: 11,
  74444. value: this._workingVector
  74445. }
  74446. ];
  74447. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74448. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74449. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74450. this._postProcessMove.animations = [];
  74451. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74452. var vignetteWeightKeys = [];
  74453. vignetteWeightKeys.push({
  74454. frame: 0,
  74455. value: 0
  74456. });
  74457. vignetteWeightKeys.push({
  74458. frame: 5,
  74459. value: 8
  74460. });
  74461. vignetteWeightKeys.push({
  74462. frame: 11,
  74463. value: 0
  74464. });
  74465. animationPP.setKeys(vignetteWeightKeys);
  74466. this._postProcessMove.animations.push(animationPP);
  74467. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74468. var vignetteStretchKeys = [];
  74469. vignetteStretchKeys.push({
  74470. frame: 0,
  74471. value: 0
  74472. });
  74473. vignetteStretchKeys.push({
  74474. frame: 5,
  74475. value: 10
  74476. });
  74477. vignetteStretchKeys.push({
  74478. frame: 11,
  74479. value: 0
  74480. });
  74481. animationPP2.setKeys(vignetteStretchKeys);
  74482. this._postProcessMove.animations.push(animationPP2);
  74483. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74484. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74485. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74486. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74487. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74488. });
  74489. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74490. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74491. });
  74492. };
  74493. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74494. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74495. return;
  74496. }
  74497. var ray;
  74498. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74499. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74500. }
  74501. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74502. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74503. }
  74504. else {
  74505. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74506. }
  74507. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74508. // Moving the gazeTracker on the mesh face targetted
  74509. if (hit && hit.pickedPoint) {
  74510. if (this._displayGaze) {
  74511. var multiplier = 1;
  74512. this._gazeTracker.isVisible = true;
  74513. if (this._isActionableMesh) {
  74514. multiplier = 3;
  74515. }
  74516. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74517. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74518. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74519. var pickNormal = hit.getNormal();
  74520. // To avoid z-fighting
  74521. var deltaFighting = 0.002;
  74522. if (pickNormal) {
  74523. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74524. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74525. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74526. }
  74527. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74528. if (this._gazeTracker.position.x < 0) {
  74529. this._gazeTracker.position.x += deltaFighting;
  74530. }
  74531. else {
  74532. this._gazeTracker.position.x -= deltaFighting;
  74533. }
  74534. if (this._gazeTracker.position.y < 0) {
  74535. this._gazeTracker.position.y += deltaFighting;
  74536. }
  74537. else {
  74538. this._gazeTracker.position.y -= deltaFighting;
  74539. }
  74540. if (this._gazeTracker.position.z < 0) {
  74541. this._gazeTracker.position.z += deltaFighting;
  74542. }
  74543. else {
  74544. this._gazeTracker.position.z -= deltaFighting;
  74545. }
  74546. }
  74547. // Changing the size of the laser pointer based on the distance from the targetted point
  74548. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74549. this._rightLaserPointer.scaling.y = hit.distance;
  74550. this._rightLaserPointer.position.z = -hit.distance / 2;
  74551. }
  74552. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74553. this._leftLaserPointer.scaling.y = hit.distance;
  74554. this._leftLaserPointer.position.z = -hit.distance / 2;
  74555. }
  74556. }
  74557. else {
  74558. this._gazeTracker.isVisible = false;
  74559. }
  74560. if (hit && hit.pickedMesh) {
  74561. this._currentHit = hit;
  74562. if (this._pointerDownOnMeshAsked) {
  74563. this._scene.simulatePointerMove(this._currentHit);
  74564. }
  74565. // The object selected is the floor, we're in a teleportation scenario
  74566. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74567. // Moving the teleportation area to this targetted point
  74568. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74569. if (this._currentMeshSelected &&
  74570. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74571. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74572. }
  74573. this._currentMeshSelected = null;
  74574. this._moveTeleportationSelectorTo(hit);
  74575. return;
  74576. }
  74577. // If not, we're in a selection scenario
  74578. this._hideTeleportationTarget();
  74579. this._teleportationAllowed = false;
  74580. if (hit.pickedMesh !== this._currentMeshSelected) {
  74581. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74582. this.onNewMeshPicked.notifyObservers(hit);
  74583. this._currentMeshSelected = hit.pickedMesh;
  74584. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74585. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74586. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74587. this._isActionableMesh = true;
  74588. }
  74589. else {
  74590. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74591. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74592. this._isActionableMesh = false;
  74593. }
  74594. try {
  74595. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74596. }
  74597. catch (err) {
  74598. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74599. }
  74600. }
  74601. else {
  74602. if (this._currentMeshSelected) {
  74603. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74604. }
  74605. this._currentMeshSelected = null;
  74606. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74607. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74608. }
  74609. }
  74610. }
  74611. else {
  74612. this._currentHit = null;
  74613. this._currentMeshSelected = null;
  74614. this._teleportationAllowed = false;
  74615. this._hideTeleportationTarget();
  74616. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74617. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74618. }
  74619. };
  74620. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74621. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74622. this._leftLaserPointer.material.emissiveColor = color;
  74623. }
  74624. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74625. this._rightLaserPointer.material.emissiveColor = color;
  74626. }
  74627. };
  74628. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74629. if (this._gazeTracker.material) {
  74630. this._gazeTracker.material.emissiveColor = color;
  74631. }
  74632. };
  74633. VRExperienceHelper.prototype.dispose = function () {
  74634. if (this.isInVRMode) {
  74635. this.exitVR();
  74636. }
  74637. if (this._passProcessMove) {
  74638. this._passProcessMove.dispose();
  74639. }
  74640. if (this._postProcessMove) {
  74641. this._postProcessMove.dispose();
  74642. }
  74643. if (this._webVRCamera) {
  74644. this._webVRCamera.dispose();
  74645. }
  74646. if (this._vrDeviceOrientationCamera) {
  74647. this._vrDeviceOrientationCamera.dispose();
  74648. }
  74649. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74650. document.body.removeChild(this._btnVR);
  74651. }
  74652. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74653. this._deviceOrientationCamera.dispose();
  74654. }
  74655. if (this._gazeTracker) {
  74656. this._gazeTracker.dispose();
  74657. }
  74658. if (this._teleportationTarget) {
  74659. this._teleportationTarget.dispose();
  74660. }
  74661. this._floorMeshesCollection = [];
  74662. document.removeEventListener("keydown", this._onKeyDown);
  74663. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74664. window.removeEventListener("resize", this._onResize);
  74665. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74666. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74667. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74668. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74669. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74670. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74671. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74672. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74673. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74674. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74675. this._scene.unregisterBeforeRender(this.beforeRender);
  74676. };
  74677. VRExperienceHelper.prototype.getClassName = function () {
  74678. return "VRExperienceHelper";
  74679. };
  74680. return VRExperienceHelper;
  74681. }());
  74682. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74683. })(BABYLON || (BABYLON = {}));
  74684. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74685. // Mainly based on these 2 articles :
  74686. // 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
  74687. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74688. var BABYLON;
  74689. (function (BABYLON) {
  74690. var JoystickAxis;
  74691. (function (JoystickAxis) {
  74692. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74693. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74694. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74695. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74696. var VirtualJoystick = /** @class */ (function () {
  74697. function VirtualJoystick(leftJoystick) {
  74698. var _this = this;
  74699. if (leftJoystick) {
  74700. this._leftJoystick = true;
  74701. }
  74702. else {
  74703. this._leftJoystick = false;
  74704. }
  74705. VirtualJoystick._globalJoystickIndex++;
  74706. // By default left & right arrow keys are moving the X
  74707. // and up & down keys are moving the Y
  74708. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74709. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74710. this.reverseLeftRight = false;
  74711. this.reverseUpDown = false;
  74712. // collections of pointers
  74713. this._touches = new BABYLON.StringDictionary();
  74714. this.deltaPosition = BABYLON.Vector3.Zero();
  74715. this._joystickSensibility = 25;
  74716. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74717. this._onResize = function (evt) {
  74718. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74719. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74720. if (VirtualJoystick.vjCanvas) {
  74721. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74722. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74723. }
  74724. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74725. };
  74726. // injecting a canvas element on top of the canvas 3D game
  74727. if (!VirtualJoystick.vjCanvas) {
  74728. window.addEventListener("resize", this._onResize, false);
  74729. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74730. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74731. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74732. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74733. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74734. VirtualJoystick.vjCanvas.style.width = "100%";
  74735. VirtualJoystick.vjCanvas.style.height = "100%";
  74736. VirtualJoystick.vjCanvas.style.position = "absolute";
  74737. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74738. VirtualJoystick.vjCanvas.style.top = "0px";
  74739. VirtualJoystick.vjCanvas.style.left = "0px";
  74740. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74741. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74742. // Support for jQuery PEP polyfill
  74743. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74744. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74745. if (!context) {
  74746. throw new Error("Unable to create canvas for virtual joystick");
  74747. }
  74748. VirtualJoystick.vjCanvasContext = context;
  74749. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74750. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74751. document.body.appendChild(VirtualJoystick.vjCanvas);
  74752. }
  74753. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74754. this.pressed = false;
  74755. // default joystick color
  74756. this._joystickColor = "cyan";
  74757. this._joystickPointerID = -1;
  74758. // current joystick position
  74759. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74760. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74761. // origin joystick position
  74762. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74763. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74764. this._onPointerDownHandlerRef = function (evt) {
  74765. _this._onPointerDown(evt);
  74766. };
  74767. this._onPointerMoveHandlerRef = function (evt) {
  74768. _this._onPointerMove(evt);
  74769. };
  74770. this._onPointerUpHandlerRef = function (evt) {
  74771. _this._onPointerUp(evt);
  74772. };
  74773. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74774. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74775. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74776. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74777. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74778. evt.preventDefault(); // Disables system menu
  74779. }, false);
  74780. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74781. }
  74782. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74783. this._joystickSensibility = newJoystickSensibility;
  74784. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74785. };
  74786. VirtualJoystick.prototype._onPointerDown = function (e) {
  74787. var positionOnScreenCondition;
  74788. e.preventDefault();
  74789. if (this._leftJoystick === true) {
  74790. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74791. }
  74792. else {
  74793. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74794. }
  74795. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74796. // First contact will be dedicated to the virtual joystick
  74797. this._joystickPointerID = e.pointerId;
  74798. this._joystickPointerStartPos.x = e.clientX;
  74799. this._joystickPointerStartPos.y = e.clientY;
  74800. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74801. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74802. this._deltaJoystickVector.x = 0;
  74803. this._deltaJoystickVector.y = 0;
  74804. this.pressed = true;
  74805. this._touches.add(e.pointerId.toString(), e);
  74806. }
  74807. else {
  74808. // You can only trigger the action buttons with a joystick declared
  74809. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74810. this._action();
  74811. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74812. }
  74813. }
  74814. };
  74815. VirtualJoystick.prototype._onPointerMove = function (e) {
  74816. // If the current pointer is the one associated to the joystick (first touch contact)
  74817. if (this._joystickPointerID == e.pointerId) {
  74818. this._joystickPointerPos.x = e.clientX;
  74819. this._joystickPointerPos.y = e.clientY;
  74820. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74821. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74822. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74823. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74824. switch (this._axisTargetedByLeftAndRight) {
  74825. case JoystickAxis.X:
  74826. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74827. break;
  74828. case JoystickAxis.Y:
  74829. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74830. break;
  74831. case JoystickAxis.Z:
  74832. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74833. break;
  74834. }
  74835. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74836. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74837. switch (this._axisTargetedByUpAndDown) {
  74838. case JoystickAxis.X:
  74839. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74840. break;
  74841. case JoystickAxis.Y:
  74842. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74843. break;
  74844. case JoystickAxis.Z:
  74845. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74846. break;
  74847. }
  74848. }
  74849. else {
  74850. var data = this._touches.get(e.pointerId.toString());
  74851. if (data) {
  74852. data.x = e.clientX;
  74853. data.y = e.clientY;
  74854. }
  74855. }
  74856. };
  74857. VirtualJoystick.prototype._onPointerUp = function (e) {
  74858. if (this._joystickPointerID == e.pointerId) {
  74859. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74860. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74861. this._joystickPointerID = -1;
  74862. this.pressed = false;
  74863. }
  74864. else {
  74865. var touch = this._touches.get(e.pointerId.toString());
  74866. if (touch) {
  74867. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74868. }
  74869. }
  74870. this._deltaJoystickVector.x = 0;
  74871. this._deltaJoystickVector.y = 0;
  74872. this._touches.remove(e.pointerId.toString());
  74873. };
  74874. /**
  74875. * Change the color of the virtual joystick
  74876. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74877. */
  74878. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74879. this._joystickColor = newColor;
  74880. };
  74881. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74882. this._action = action;
  74883. };
  74884. // Define which axis you'd like to control for left & right
  74885. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74886. switch (axis) {
  74887. case JoystickAxis.X:
  74888. case JoystickAxis.Y:
  74889. case JoystickAxis.Z:
  74890. this._axisTargetedByLeftAndRight = axis;
  74891. break;
  74892. default:
  74893. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74894. break;
  74895. }
  74896. };
  74897. // Define which axis you'd like to control for up & down
  74898. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74899. switch (axis) {
  74900. case JoystickAxis.X:
  74901. case JoystickAxis.Y:
  74902. case JoystickAxis.Z:
  74903. this._axisTargetedByUpAndDown = axis;
  74904. break;
  74905. default:
  74906. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74907. break;
  74908. }
  74909. };
  74910. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74911. var _this = this;
  74912. if (this.pressed) {
  74913. this._touches.forEach(function (key, touch) {
  74914. if (touch.pointerId === _this._joystickPointerID) {
  74915. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74916. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74917. VirtualJoystick.vjCanvasContext.beginPath();
  74918. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74919. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74920. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74921. VirtualJoystick.vjCanvasContext.stroke();
  74922. VirtualJoystick.vjCanvasContext.closePath();
  74923. VirtualJoystick.vjCanvasContext.beginPath();
  74924. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74925. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74926. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74927. VirtualJoystick.vjCanvasContext.stroke();
  74928. VirtualJoystick.vjCanvasContext.closePath();
  74929. VirtualJoystick.vjCanvasContext.beginPath();
  74930. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74931. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74932. VirtualJoystick.vjCanvasContext.stroke();
  74933. VirtualJoystick.vjCanvasContext.closePath();
  74934. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74935. }
  74936. else {
  74937. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74938. VirtualJoystick.vjCanvasContext.beginPath();
  74939. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74940. VirtualJoystick.vjCanvasContext.beginPath();
  74941. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74942. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74943. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74944. VirtualJoystick.vjCanvasContext.stroke();
  74945. VirtualJoystick.vjCanvasContext.closePath();
  74946. touch.prevX = touch.x;
  74947. touch.prevY = touch.y;
  74948. }
  74949. ;
  74950. });
  74951. }
  74952. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74953. };
  74954. VirtualJoystick.prototype.releaseCanvas = function () {
  74955. if (VirtualJoystick.vjCanvas) {
  74956. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74957. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74958. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74959. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74960. window.removeEventListener("resize", this._onResize);
  74961. document.body.removeChild(VirtualJoystick.vjCanvas);
  74962. VirtualJoystick.vjCanvas = null;
  74963. }
  74964. };
  74965. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74966. VirtualJoystick._globalJoystickIndex = 0;
  74967. return VirtualJoystick;
  74968. }());
  74969. BABYLON.VirtualJoystick = VirtualJoystick;
  74970. })(BABYLON || (BABYLON = {}));
  74971. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74972. var BABYLON;
  74973. (function (BABYLON) {
  74974. // We're mainly based on the logic defined into the FreeCamera code
  74975. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74976. __extends(VirtualJoysticksCamera, _super);
  74977. function VirtualJoysticksCamera(name, position, scene) {
  74978. var _this = _super.call(this, name, position, scene) || this;
  74979. _this.inputs.addVirtualJoystick();
  74980. return _this;
  74981. }
  74982. VirtualJoysticksCamera.prototype.getClassName = function () {
  74983. return "VirtualJoysticksCamera";
  74984. };
  74985. return VirtualJoysticksCamera;
  74986. }(BABYLON.FreeCamera));
  74987. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74988. })(BABYLON || (BABYLON = {}));
  74989. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74990. var BABYLON;
  74991. (function (BABYLON) {
  74992. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74993. function FreeCameraVirtualJoystickInput() {
  74994. }
  74995. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74996. return this._leftjoystick;
  74997. };
  74998. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74999. return this._rightjoystick;
  75000. };
  75001. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  75002. if (this._leftjoystick) {
  75003. var camera = this.camera;
  75004. var speed = camera._computeLocalCameraSpeed() * 50;
  75005. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  75006. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  75007. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  75008. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  75009. if (!this._leftjoystick.pressed) {
  75010. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  75011. }
  75012. if (!this._rightjoystick.pressed) {
  75013. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  75014. }
  75015. }
  75016. };
  75017. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  75018. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  75019. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  75020. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  75021. this._leftjoystick.setJoystickSensibility(0.15);
  75022. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  75023. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  75024. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  75025. this._rightjoystick.reverseUpDown = true;
  75026. this._rightjoystick.setJoystickSensibility(0.05);
  75027. this._rightjoystick.setJoystickColor("yellow");
  75028. };
  75029. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  75030. this._leftjoystick.releaseCanvas();
  75031. this._rightjoystick.releaseCanvas();
  75032. };
  75033. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  75034. return "FreeCameraVirtualJoystickInput";
  75035. };
  75036. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  75037. return "virtualJoystick";
  75038. };
  75039. return FreeCameraVirtualJoystickInput;
  75040. }());
  75041. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  75042. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  75043. })(BABYLON || (BABYLON = {}));
  75044. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  75045. var BABYLON;
  75046. (function (BABYLON) {
  75047. var SimplificationSettings = /** @class */ (function () {
  75048. function SimplificationSettings(quality, distance, optimizeMesh) {
  75049. this.quality = quality;
  75050. this.distance = distance;
  75051. this.optimizeMesh = optimizeMesh;
  75052. }
  75053. return SimplificationSettings;
  75054. }());
  75055. BABYLON.SimplificationSettings = SimplificationSettings;
  75056. var SimplificationQueue = /** @class */ (function () {
  75057. function SimplificationQueue() {
  75058. this.running = false;
  75059. this._simplificationArray = [];
  75060. }
  75061. SimplificationQueue.prototype.addTask = function (task) {
  75062. this._simplificationArray.push(task);
  75063. };
  75064. SimplificationQueue.prototype.executeNext = function () {
  75065. var task = this._simplificationArray.pop();
  75066. if (task) {
  75067. this.running = true;
  75068. this.runSimplification(task);
  75069. }
  75070. else {
  75071. this.running = false;
  75072. }
  75073. };
  75074. SimplificationQueue.prototype.runSimplification = function (task) {
  75075. var _this = this;
  75076. if (task.parallelProcessing) {
  75077. //parallel simplifier
  75078. task.settings.forEach(function (setting) {
  75079. var simplifier = _this.getSimplifier(task);
  75080. simplifier.simplify(setting, function (newMesh) {
  75081. task.mesh.addLODLevel(setting.distance, newMesh);
  75082. newMesh.isVisible = true;
  75083. //check if it is the last
  75084. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  75085. //all done, run the success callback.
  75086. task.successCallback();
  75087. }
  75088. _this.executeNext();
  75089. });
  75090. });
  75091. }
  75092. else {
  75093. //single simplifier.
  75094. var simplifier = this.getSimplifier(task);
  75095. var runDecimation = function (setting, callback) {
  75096. simplifier.simplify(setting, function (newMesh) {
  75097. task.mesh.addLODLevel(setting.distance, newMesh);
  75098. newMesh.isVisible = true;
  75099. //run the next quality level
  75100. callback();
  75101. });
  75102. };
  75103. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  75104. runDecimation(task.settings[loop.index], function () {
  75105. loop.executeNext();
  75106. });
  75107. }, function () {
  75108. //execution ended, run the success callback.
  75109. if (task.successCallback) {
  75110. task.successCallback();
  75111. }
  75112. _this.executeNext();
  75113. });
  75114. }
  75115. };
  75116. SimplificationQueue.prototype.getSimplifier = function (task) {
  75117. switch (task.simplificationType) {
  75118. case SimplificationType.QUADRATIC:
  75119. default:
  75120. return new QuadraticErrorSimplification(task.mesh);
  75121. }
  75122. };
  75123. return SimplificationQueue;
  75124. }());
  75125. BABYLON.SimplificationQueue = SimplificationQueue;
  75126. /**
  75127. * The implemented types of simplification.
  75128. * At the moment only Quadratic Error Decimation is implemented.
  75129. */
  75130. var SimplificationType;
  75131. (function (SimplificationType) {
  75132. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  75133. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  75134. var DecimationTriangle = /** @class */ (function () {
  75135. function DecimationTriangle(vertices) {
  75136. this.vertices = vertices;
  75137. this.error = new Array(4);
  75138. this.deleted = false;
  75139. this.isDirty = false;
  75140. this.deletePending = false;
  75141. this.borderFactor = 0;
  75142. }
  75143. return DecimationTriangle;
  75144. }());
  75145. BABYLON.DecimationTriangle = DecimationTriangle;
  75146. var DecimationVertex = /** @class */ (function () {
  75147. function DecimationVertex(position, id) {
  75148. this.position = position;
  75149. this.id = id;
  75150. this.isBorder = true;
  75151. this.q = new QuadraticMatrix();
  75152. this.triangleCount = 0;
  75153. this.triangleStart = 0;
  75154. this.originalOffsets = [];
  75155. }
  75156. DecimationVertex.prototype.updatePosition = function (newPosition) {
  75157. this.position.copyFrom(newPosition);
  75158. };
  75159. return DecimationVertex;
  75160. }());
  75161. BABYLON.DecimationVertex = DecimationVertex;
  75162. var QuadraticMatrix = /** @class */ (function () {
  75163. function QuadraticMatrix(data) {
  75164. this.data = new Array(10);
  75165. for (var i = 0; i < 10; ++i) {
  75166. if (data && data[i]) {
  75167. this.data[i] = data[i];
  75168. }
  75169. else {
  75170. this.data[i] = 0;
  75171. }
  75172. }
  75173. }
  75174. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  75175. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  75176. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  75177. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  75178. return det;
  75179. };
  75180. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  75181. for (var i = 0; i < 10; ++i) {
  75182. this.data[i] += matrix.data[i];
  75183. }
  75184. };
  75185. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  75186. for (var i = 0; i < 10; ++i) {
  75187. this.data[i] += data[i];
  75188. }
  75189. };
  75190. QuadraticMatrix.prototype.add = function (matrix) {
  75191. var m = new QuadraticMatrix();
  75192. for (var i = 0; i < 10; ++i) {
  75193. m.data[i] = this.data[i] + matrix.data[i];
  75194. }
  75195. return m;
  75196. };
  75197. QuadraticMatrix.FromData = function (a, b, c, d) {
  75198. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  75199. };
  75200. //returning an array to avoid garbage collection
  75201. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  75202. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  75203. };
  75204. return QuadraticMatrix;
  75205. }());
  75206. BABYLON.QuadraticMatrix = QuadraticMatrix;
  75207. var Reference = /** @class */ (function () {
  75208. function Reference(vertexId, triangleId) {
  75209. this.vertexId = vertexId;
  75210. this.triangleId = triangleId;
  75211. }
  75212. return Reference;
  75213. }());
  75214. BABYLON.Reference = Reference;
  75215. /**
  75216. * An implementation of the Quadratic Error simplification algorithm.
  75217. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  75218. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  75219. * @author RaananW
  75220. */
  75221. var QuadraticErrorSimplification = /** @class */ (function () {
  75222. function QuadraticErrorSimplification(_mesh) {
  75223. this._mesh = _mesh;
  75224. this.syncIterations = 5000;
  75225. this.aggressiveness = 7;
  75226. this.decimationIterations = 100;
  75227. this.boundingBoxEpsilon = BABYLON.Epsilon;
  75228. }
  75229. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  75230. var _this = this;
  75231. this.initDecimatedMesh();
  75232. //iterating through the submeshes array, one after the other.
  75233. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  75234. _this.initWithMesh(loop.index, function () {
  75235. _this.runDecimation(settings, loop.index, function () {
  75236. loop.executeNext();
  75237. });
  75238. }, settings.optimizeMesh);
  75239. }, function () {
  75240. setTimeout(function () {
  75241. successCallback(_this._reconstructedMesh);
  75242. }, 0);
  75243. });
  75244. };
  75245. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75246. var _this = this;
  75247. var targetCount = ~~(this.triangles.length * settings.quality);
  75248. var deletedTriangles = 0;
  75249. var triangleCount = this.triangles.length;
  75250. var iterationFunction = function (iteration, callback) {
  75251. setTimeout(function () {
  75252. if (iteration % 5 === 0) {
  75253. _this.updateMesh(iteration === 0);
  75254. }
  75255. for (var i = 0; i < _this.triangles.length; ++i) {
  75256. _this.triangles[i].isDirty = false;
  75257. }
  75258. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75259. var trianglesIterator = function (i) {
  75260. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75261. var t = _this.triangles[tIdx];
  75262. if (!t)
  75263. return;
  75264. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75265. return;
  75266. }
  75267. for (var j = 0; j < 3; ++j) {
  75268. if (t.error[j] < threshold) {
  75269. var deleted0 = [];
  75270. var deleted1 = [];
  75271. var v0 = t.vertices[j];
  75272. var v1 = t.vertices[(j + 1) % 3];
  75273. if (v0.isBorder || v1.isBorder)
  75274. continue;
  75275. var p = BABYLON.Vector3.Zero();
  75276. var n = BABYLON.Vector3.Zero();
  75277. var uv = BABYLON.Vector2.Zero();
  75278. var color = new BABYLON.Color4(0, 0, 0, 1);
  75279. _this.calculateError(v0, v1, p, n, uv, color);
  75280. var delTr = new Array();
  75281. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75282. continue;
  75283. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75284. continue;
  75285. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75286. continue;
  75287. var uniqueArray = new Array();
  75288. delTr.forEach(function (deletedT) {
  75289. if (uniqueArray.indexOf(deletedT) === -1) {
  75290. deletedT.deletePending = true;
  75291. uniqueArray.push(deletedT);
  75292. }
  75293. });
  75294. if (uniqueArray.length % 2 !== 0) {
  75295. continue;
  75296. }
  75297. v0.q = v1.q.add(v0.q);
  75298. v0.updatePosition(p);
  75299. var tStart = _this.references.length;
  75300. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75301. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75302. var tCount = _this.references.length - tStart;
  75303. if (tCount <= v0.triangleCount) {
  75304. if (tCount) {
  75305. for (var c = 0; c < tCount; c++) {
  75306. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75307. }
  75308. }
  75309. }
  75310. else {
  75311. v0.triangleStart = tStart;
  75312. }
  75313. v0.triangleCount = tCount;
  75314. break;
  75315. }
  75316. }
  75317. };
  75318. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75319. }, 0);
  75320. };
  75321. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75322. if (triangleCount - deletedTriangles <= targetCount)
  75323. loop.breakLoop();
  75324. else {
  75325. iterationFunction(loop.index, function () {
  75326. loop.executeNext();
  75327. });
  75328. }
  75329. }, function () {
  75330. setTimeout(function () {
  75331. //reconstruct this part of the mesh
  75332. _this.reconstructMesh(submeshIndex);
  75333. successCallback();
  75334. }, 0);
  75335. });
  75336. };
  75337. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75338. var _this = this;
  75339. this.vertices = [];
  75340. this.triangles = [];
  75341. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75342. var indices = this._mesh.getIndices();
  75343. var submesh = this._mesh.subMeshes[submeshIndex];
  75344. var findInVertices = function (positionToSearch) {
  75345. if (optimizeMesh) {
  75346. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75347. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75348. return _this.vertices[ii];
  75349. }
  75350. }
  75351. }
  75352. return null;
  75353. };
  75354. var vertexReferences = [];
  75355. var vertexInit = function (i) {
  75356. if (!positionData) {
  75357. return;
  75358. }
  75359. var offset = i + submesh.verticesStart;
  75360. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75361. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75362. vertex.originalOffsets.push(offset);
  75363. if (vertex.id === _this.vertices.length) {
  75364. _this.vertices.push(vertex);
  75365. }
  75366. vertexReferences.push(vertex.id);
  75367. };
  75368. //var totalVertices = mesh.getTotalVertices();
  75369. var totalVertices = submesh.verticesCount;
  75370. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75371. var indicesInit = function (i) {
  75372. if (!indices) {
  75373. return;
  75374. }
  75375. var offset = (submesh.indexStart / 3) + i;
  75376. var pos = (offset * 3);
  75377. var i0 = indices[pos + 0];
  75378. var i1 = indices[pos + 1];
  75379. var i2 = indices[pos + 2];
  75380. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75381. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75382. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75383. var triangle = new DecimationTriangle([v0, v1, v2]);
  75384. triangle.originalOffset = pos;
  75385. _this.triangles.push(triangle);
  75386. };
  75387. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75388. _this.init(callback);
  75389. });
  75390. });
  75391. };
  75392. QuadraticErrorSimplification.prototype.init = function (callback) {
  75393. var _this = this;
  75394. var triangleInit1 = function (i) {
  75395. var t = _this.triangles[i];
  75396. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75397. for (var j = 0; j < 3; j++) {
  75398. 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))));
  75399. }
  75400. };
  75401. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75402. var triangleInit2 = function (i) {
  75403. var t = _this.triangles[i];
  75404. for (var j = 0; j < 3; ++j) {
  75405. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75406. }
  75407. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75408. };
  75409. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75410. callback();
  75411. });
  75412. });
  75413. };
  75414. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75415. var newTriangles = [];
  75416. var i;
  75417. for (i = 0; i < this.vertices.length; ++i) {
  75418. this.vertices[i].triangleCount = 0;
  75419. }
  75420. var t;
  75421. var j;
  75422. for (i = 0; i < this.triangles.length; ++i) {
  75423. if (!this.triangles[i].deleted) {
  75424. t = this.triangles[i];
  75425. for (j = 0; j < 3; ++j) {
  75426. t.vertices[j].triangleCount = 1;
  75427. }
  75428. newTriangles.push(t);
  75429. }
  75430. }
  75431. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75432. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75433. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75434. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75435. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75436. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75437. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75438. var vertexCount = 0;
  75439. for (i = 0; i < this.vertices.length; ++i) {
  75440. var vertex = this.vertices[i];
  75441. vertex.id = vertexCount;
  75442. if (vertex.triangleCount) {
  75443. vertex.originalOffsets.forEach(function (originalOffset) {
  75444. if (!normalData) {
  75445. return;
  75446. }
  75447. newPositionData.push(vertex.position.x);
  75448. newPositionData.push(vertex.position.y);
  75449. newPositionData.push(vertex.position.z);
  75450. newNormalData.push(normalData[originalOffset * 3]);
  75451. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75452. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75453. if (uvs && uvs.length) {
  75454. newUVsData.push(uvs[(originalOffset * 2)]);
  75455. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75456. }
  75457. else if (colorsData && colorsData.length) {
  75458. newColorsData.push(colorsData[(originalOffset * 4)]);
  75459. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75460. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75461. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75462. }
  75463. ++vertexCount;
  75464. });
  75465. }
  75466. }
  75467. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75468. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75469. var submeshesArray = this._reconstructedMesh.subMeshes;
  75470. this._reconstructedMesh.subMeshes = [];
  75471. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75472. var originalIndices = this._mesh.getIndices();
  75473. for (i = 0; i < newTriangles.length; ++i) {
  75474. t = newTriangles[i]; //now get the new referencing point for each vertex
  75475. [0, 1, 2].forEach(function (idx) {
  75476. var id = originalIndices[t.originalOffset + idx];
  75477. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75478. if (offset < 0)
  75479. offset = 0;
  75480. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75481. });
  75482. }
  75483. //overwriting the old vertex buffers and indices.
  75484. this._reconstructedMesh.setIndices(newIndicesArray);
  75485. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75486. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75487. if (newUVsData.length > 0)
  75488. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75489. if (newColorsData.length > 0)
  75490. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75491. //create submesh
  75492. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75493. if (submeshIndex > 0) {
  75494. this._reconstructedMesh.subMeshes = [];
  75495. submeshesArray.forEach(function (submesh) {
  75496. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75497. });
  75498. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75499. }
  75500. };
  75501. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75502. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75503. this._reconstructedMesh.material = this._mesh.material;
  75504. this._reconstructedMesh.parent = this._mesh.parent;
  75505. this._reconstructedMesh.isVisible = false;
  75506. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75507. };
  75508. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75509. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75510. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75511. if (t.deleted)
  75512. continue;
  75513. var s = this.references[vertex1.triangleStart + i].vertexId;
  75514. var v1 = t.vertices[(s + 1) % 3];
  75515. var v2 = t.vertices[(s + 2) % 3];
  75516. if ((v1 === vertex2 || v2 === vertex2)) {
  75517. deletedArray[i] = true;
  75518. delTr.push(t);
  75519. continue;
  75520. }
  75521. var d1 = v1.position.subtract(point);
  75522. d1 = d1.normalize();
  75523. var d2 = v2.position.subtract(point);
  75524. d2 = d2.normalize();
  75525. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75526. return true;
  75527. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75528. deletedArray[i] = false;
  75529. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75530. return true;
  75531. }
  75532. return false;
  75533. };
  75534. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75535. var newDeleted = deletedTriangles;
  75536. for (var i = 0; i < vertex.triangleCount; ++i) {
  75537. var ref = this.references[vertex.triangleStart + i];
  75538. var t = this.triangles[ref.triangleId];
  75539. if (t.deleted)
  75540. continue;
  75541. if (deletedArray[i] && t.deletePending) {
  75542. t.deleted = true;
  75543. newDeleted++;
  75544. continue;
  75545. }
  75546. t.vertices[ref.vertexId] = origVertex;
  75547. t.isDirty = true;
  75548. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75549. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75550. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75551. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75552. this.references.push(ref);
  75553. }
  75554. return newDeleted;
  75555. };
  75556. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75557. for (var i = 0; i < this.vertices.length; ++i) {
  75558. var vCount = [];
  75559. var vId = [];
  75560. var v = this.vertices[i];
  75561. var j;
  75562. for (j = 0; j < v.triangleCount; ++j) {
  75563. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75564. for (var ii = 0; ii < 3; ii++) {
  75565. var ofs = 0;
  75566. var vv = triangle.vertices[ii];
  75567. while (ofs < vCount.length) {
  75568. if (vId[ofs] === vv.id)
  75569. break;
  75570. ++ofs;
  75571. }
  75572. if (ofs === vCount.length) {
  75573. vCount.push(1);
  75574. vId.push(vv.id);
  75575. }
  75576. else {
  75577. vCount[ofs]++;
  75578. }
  75579. }
  75580. }
  75581. for (j = 0; j < vCount.length; ++j) {
  75582. if (vCount[j] === 1) {
  75583. this.vertices[vId[j]].isBorder = true;
  75584. }
  75585. else {
  75586. this.vertices[vId[j]].isBorder = false;
  75587. }
  75588. }
  75589. }
  75590. };
  75591. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75592. if (identifyBorders === void 0) { identifyBorders = false; }
  75593. var i;
  75594. if (!identifyBorders) {
  75595. var newTrianglesVector = [];
  75596. for (i = 0; i < this.triangles.length; ++i) {
  75597. if (!this.triangles[i].deleted) {
  75598. newTrianglesVector.push(this.triangles[i]);
  75599. }
  75600. }
  75601. this.triangles = newTrianglesVector;
  75602. }
  75603. for (i = 0; i < this.vertices.length; ++i) {
  75604. this.vertices[i].triangleCount = 0;
  75605. this.vertices[i].triangleStart = 0;
  75606. }
  75607. var t;
  75608. var j;
  75609. var v;
  75610. for (i = 0; i < this.triangles.length; ++i) {
  75611. t = this.triangles[i];
  75612. for (j = 0; j < 3; ++j) {
  75613. v = t.vertices[j];
  75614. v.triangleCount++;
  75615. }
  75616. }
  75617. var tStart = 0;
  75618. for (i = 0; i < this.vertices.length; ++i) {
  75619. this.vertices[i].triangleStart = tStart;
  75620. tStart += this.vertices[i].triangleCount;
  75621. this.vertices[i].triangleCount = 0;
  75622. }
  75623. var newReferences = new Array(this.triangles.length * 3);
  75624. for (i = 0; i < this.triangles.length; ++i) {
  75625. t = this.triangles[i];
  75626. for (j = 0; j < 3; ++j) {
  75627. v = t.vertices[j];
  75628. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75629. v.triangleCount++;
  75630. }
  75631. }
  75632. this.references = newReferences;
  75633. if (identifyBorders) {
  75634. this.identifyBorder();
  75635. }
  75636. };
  75637. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75638. var x = point.x;
  75639. var y = point.y;
  75640. var z = point.z;
  75641. 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
  75642. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75643. };
  75644. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75645. var q = vertex1.q.add(vertex2.q);
  75646. var border = vertex1.isBorder && vertex2.isBorder;
  75647. var error = 0;
  75648. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75649. if (qDet !== 0 && !border) {
  75650. if (!pointResult) {
  75651. pointResult = BABYLON.Vector3.Zero();
  75652. }
  75653. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75654. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75655. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75656. error = this.vertexError(q, pointResult);
  75657. }
  75658. else {
  75659. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75660. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75661. var error1 = this.vertexError(q, vertex1.position);
  75662. var error2 = this.vertexError(q, vertex2.position);
  75663. var error3 = this.vertexError(q, p3);
  75664. error = Math.min(error1, error2, error3);
  75665. if (error === error1) {
  75666. if (pointResult) {
  75667. pointResult.copyFrom(vertex1.position);
  75668. }
  75669. }
  75670. else if (error === error2) {
  75671. if (pointResult) {
  75672. pointResult.copyFrom(vertex2.position);
  75673. }
  75674. }
  75675. else {
  75676. if (pointResult) {
  75677. pointResult.copyFrom(p3);
  75678. }
  75679. }
  75680. }
  75681. return error;
  75682. };
  75683. return QuadraticErrorSimplification;
  75684. }());
  75685. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75686. })(BABYLON || (BABYLON = {}));
  75687. //# sourceMappingURL=babylon.meshSimplification.js.map
  75688. var BABYLON;
  75689. (function (BABYLON) {
  75690. var MeshLODLevel = /** @class */ (function () {
  75691. function MeshLODLevel(distance, mesh) {
  75692. this.distance = distance;
  75693. this.mesh = mesh;
  75694. }
  75695. return MeshLODLevel;
  75696. }());
  75697. BABYLON.MeshLODLevel = MeshLODLevel;
  75698. })(BABYLON || (BABYLON = {}));
  75699. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75700. var BABYLON;
  75701. (function (BABYLON) {
  75702. /**
  75703. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75704. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75705. */
  75706. var SceneOptimization = /** @class */ (function () {
  75707. /**
  75708. * Creates the SceneOptimization object
  75709. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75710. * @param desc defines the description associated with the optimization
  75711. */
  75712. function SceneOptimization(priority) {
  75713. if (priority === void 0) { priority = 0; }
  75714. this.priority = priority;
  75715. }
  75716. /**
  75717. * Gets a string describing the action executed by the current optimization
  75718. */
  75719. SceneOptimization.prototype.getDescription = function () {
  75720. return "";
  75721. };
  75722. /**
  75723. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75724. * @param scene defines the current scene where to apply this optimization
  75725. * @returnstrue if everything that can be done was applied
  75726. */
  75727. SceneOptimization.prototype.apply = function (scene) {
  75728. return true;
  75729. };
  75730. ;
  75731. return SceneOptimization;
  75732. }());
  75733. BABYLON.SceneOptimization = SceneOptimization;
  75734. /**
  75735. * Defines an optimization used to reduce the size of render target textures
  75736. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75737. */
  75738. var TextureOptimization = /** @class */ (function (_super) {
  75739. __extends(TextureOptimization, _super);
  75740. /**
  75741. * Creates the TextureOptimization object
  75742. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75743. * @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
  75744. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75745. */
  75746. function TextureOptimization(priority, maximumSize, step) {
  75747. if (priority === void 0) { priority = 0; }
  75748. if (maximumSize === void 0) { maximumSize = 1024; }
  75749. if (step === void 0) { step = 0.5; }
  75750. var _this = _super.call(this, priority) || this;
  75751. _this.priority = priority;
  75752. _this.maximumSize = maximumSize;
  75753. _this.step = step;
  75754. return _this;
  75755. }
  75756. /**
  75757. * Gets a string describing the action executed by the current optimization
  75758. */
  75759. TextureOptimization.prototype.getDescription = function () {
  75760. return "Reducing render target texture size to " + this.maximumSize;
  75761. };
  75762. /**
  75763. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75764. * @param scene defines the current scene where to apply this optimization
  75765. */
  75766. TextureOptimization.prototype.apply = function (scene) {
  75767. var allDone = true;
  75768. for (var index = 0; index < scene.textures.length; index++) {
  75769. var texture = scene.textures[index];
  75770. if (!texture.canRescale || texture.getContext) {
  75771. continue;
  75772. }
  75773. var currentSize = texture.getSize();
  75774. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75775. if (maxDimension > this.maximumSize) {
  75776. texture.scale(this.step);
  75777. allDone = false;
  75778. }
  75779. }
  75780. return allDone;
  75781. };
  75782. return TextureOptimization;
  75783. }(SceneOptimization));
  75784. BABYLON.TextureOptimization = TextureOptimization;
  75785. /**
  75786. * Defines an optimization used to increase or decrease the rendering resolution
  75787. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75788. */
  75789. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75790. __extends(HardwareScalingOptimization, _super);
  75791. /**
  75792. * Creates the HardwareScalingOptimization object
  75793. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75794. * @param maximumScale
  75795. * @param step
  75796. */
  75797. function HardwareScalingOptimization(priority, maximumScale, step) {
  75798. if (priority === void 0) { priority = 0; }
  75799. if (maximumScale === void 0) { maximumScale = 2; }
  75800. if (step === void 0) { step = 0.25; }
  75801. var _this = _super.call(this, priority) || this;
  75802. _this.priority = priority;
  75803. _this.maximumScale = maximumScale;
  75804. _this.step = step;
  75805. _this._currentScale = -1;
  75806. _this._directionOffset = 1;
  75807. return _this;
  75808. }
  75809. /**
  75810. * Gets a string describing the action executed by the current optimization
  75811. */
  75812. HardwareScalingOptimization.prototype.getDescription = function () {
  75813. return "Setting hardware scaling level to " + this._currentScale;
  75814. };
  75815. /**
  75816. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75817. * @param scene defines the current scene where to apply this optimization
  75818. */
  75819. HardwareScalingOptimization.prototype.apply = function (scene) {
  75820. if (this._currentScale === -1) {
  75821. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75822. if (this._currentScale > this.maximumScale) {
  75823. this._directionOffset = -1;
  75824. }
  75825. }
  75826. this._currentScale += this._directionOffset * this.step;
  75827. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75828. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75829. };
  75830. ;
  75831. return HardwareScalingOptimization;
  75832. }(SceneOptimization));
  75833. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75834. /**
  75835. * Defines an optimization used to remove shadows
  75836. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75837. */
  75838. var ShadowsOptimization = /** @class */ (function (_super) {
  75839. __extends(ShadowsOptimization, _super);
  75840. function ShadowsOptimization() {
  75841. return _super !== null && _super.apply(this, arguments) || this;
  75842. }
  75843. /**
  75844. * Gets a string describing the action executed by the current optimization
  75845. */
  75846. ShadowsOptimization.prototype.getDescription = function () {
  75847. return "Turning shadows off";
  75848. };
  75849. /**
  75850. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75851. * @param scene defines the current scene where to apply this optimization
  75852. */
  75853. ShadowsOptimization.prototype.apply = function (scene) {
  75854. scene.shadowsEnabled = false;
  75855. return true;
  75856. };
  75857. ;
  75858. return ShadowsOptimization;
  75859. }(SceneOptimization));
  75860. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75861. /**
  75862. * Defines an optimization used to turn post-processes off
  75863. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75864. */
  75865. var PostProcessesOptimization = /** @class */ (function (_super) {
  75866. __extends(PostProcessesOptimization, _super);
  75867. function PostProcessesOptimization() {
  75868. return _super !== null && _super.apply(this, arguments) || this;
  75869. }
  75870. /**
  75871. * Gets a string describing the action executed by the current optimization
  75872. */
  75873. PostProcessesOptimization.prototype.getDescription = function () {
  75874. return "Turning post-processes off";
  75875. };
  75876. /**
  75877. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75878. * @param scene defines the current scene where to apply this optimization
  75879. */
  75880. PostProcessesOptimization.prototype.apply = function (scene) {
  75881. scene.postProcessesEnabled = false;
  75882. return true;
  75883. };
  75884. ;
  75885. return PostProcessesOptimization;
  75886. }(SceneOptimization));
  75887. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75888. /**
  75889. * Defines an optimization used to turn lens flares off
  75890. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75891. */
  75892. var LensFlaresOptimization = /** @class */ (function (_super) {
  75893. __extends(LensFlaresOptimization, _super);
  75894. function LensFlaresOptimization() {
  75895. return _super !== null && _super.apply(this, arguments) || this;
  75896. }
  75897. /**
  75898. * Gets a string describing the action executed by the current optimization
  75899. */
  75900. LensFlaresOptimization.prototype.getDescription = function () {
  75901. return "Turning lens flares off";
  75902. };
  75903. /**
  75904. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75905. * @param scene defines the current scene where to apply this optimization
  75906. */
  75907. LensFlaresOptimization.prototype.apply = function (scene) {
  75908. scene.lensFlaresEnabled = false;
  75909. return true;
  75910. };
  75911. ;
  75912. return LensFlaresOptimization;
  75913. }(SceneOptimization));
  75914. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75915. /**
  75916. * Defines an optimization based on user defined callback.
  75917. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75918. */
  75919. var CustomOptimization = /** @class */ (function (_super) {
  75920. __extends(CustomOptimization, _super);
  75921. function CustomOptimization() {
  75922. return _super !== null && _super.apply(this, arguments) || this;
  75923. }
  75924. /**
  75925. * Gets a string describing the action executed by the current optimization
  75926. */
  75927. CustomOptimization.prototype.getDescription = function () {
  75928. if (this.onGetDescription) {
  75929. return this.onGetDescription();
  75930. }
  75931. return "Running user defined callback";
  75932. };
  75933. /**
  75934. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75935. * @param scene defines the current scene where to apply this optimization
  75936. */
  75937. CustomOptimization.prototype.apply = function (scene) {
  75938. if (this.onApply) {
  75939. return this.onApply(scene);
  75940. }
  75941. return true;
  75942. };
  75943. ;
  75944. return CustomOptimization;
  75945. }(SceneOptimization));
  75946. BABYLON.CustomOptimization = CustomOptimization;
  75947. /**
  75948. * Defines an optimization used to turn particles off
  75949. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75950. */
  75951. var ParticlesOptimization = /** @class */ (function (_super) {
  75952. __extends(ParticlesOptimization, _super);
  75953. function ParticlesOptimization() {
  75954. return _super !== null && _super.apply(this, arguments) || this;
  75955. }
  75956. /**
  75957. * Gets a string describing the action executed by the current optimization
  75958. */
  75959. ParticlesOptimization.prototype.getDescription = function () {
  75960. return "Turning particles off";
  75961. };
  75962. /**
  75963. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75964. * @param scene defines the current scene where to apply this optimization
  75965. */
  75966. ParticlesOptimization.prototype.apply = function (scene) {
  75967. scene.particlesEnabled = false;
  75968. return true;
  75969. };
  75970. ;
  75971. return ParticlesOptimization;
  75972. }(SceneOptimization));
  75973. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75974. /**
  75975. * Defines an optimization used to turn render targets off
  75976. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75977. */
  75978. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75979. __extends(RenderTargetsOptimization, _super);
  75980. function RenderTargetsOptimization() {
  75981. return _super !== null && _super.apply(this, arguments) || this;
  75982. }
  75983. /**
  75984. * Gets a string describing the action executed by the current optimization
  75985. */
  75986. RenderTargetsOptimization.prototype.getDescription = function () {
  75987. return "Turning render targets off";
  75988. };
  75989. /**
  75990. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75991. * @param scene defines the current scene where to apply this optimization
  75992. */
  75993. RenderTargetsOptimization.prototype.apply = function (scene) {
  75994. scene.renderTargetsEnabled = false;
  75995. return true;
  75996. };
  75997. ;
  75998. return RenderTargetsOptimization;
  75999. }(SceneOptimization));
  76000. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  76001. /**
  76002. * Defines an optimization used to merge meshes with compatible materials
  76003. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76004. */
  76005. var MergeMeshesOptimization = /** @class */ (function (_super) {
  76006. __extends(MergeMeshesOptimization, _super);
  76007. function MergeMeshesOptimization() {
  76008. var _this = _super !== null && _super.apply(this, arguments) || this;
  76009. _this._canBeMerged = function (abstractMesh) {
  76010. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  76011. return false;
  76012. }
  76013. var mesh = abstractMesh;
  76014. if (!mesh.isVisible || !mesh.isEnabled()) {
  76015. return false;
  76016. }
  76017. if (mesh.instances.length > 0) {
  76018. return false;
  76019. }
  76020. if (mesh.skeleton || mesh.hasLODLevels) {
  76021. return false;
  76022. }
  76023. if (mesh.parent) {
  76024. return false;
  76025. }
  76026. return true;
  76027. };
  76028. return _this;
  76029. }
  76030. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  76031. /**
  76032. * Gets or sets a boolean which defines if optimization octree has to be updated
  76033. */
  76034. get: function () {
  76035. return MergeMeshesOptimization._UpdateSelectionTree;
  76036. },
  76037. /**
  76038. * Gets or sets a boolean which defines if optimization octree has to be updated
  76039. */
  76040. set: function (value) {
  76041. MergeMeshesOptimization._UpdateSelectionTree = value;
  76042. },
  76043. enumerable: true,
  76044. configurable: true
  76045. });
  76046. /**
  76047. * Gets a string describing the action executed by the current optimization
  76048. */
  76049. MergeMeshesOptimization.prototype.getDescription = function () {
  76050. return "Merging similar meshes together";
  76051. };
  76052. /**
  76053. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  76054. * @param scene defines the current scene where to apply this optimization
  76055. */
  76056. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  76057. var globalPool = scene.meshes.slice(0);
  76058. var globalLength = globalPool.length;
  76059. for (var index = 0; index < globalLength; index++) {
  76060. var currentPool = new Array();
  76061. var current = globalPool[index];
  76062. // Checks
  76063. if (!this._canBeMerged(current)) {
  76064. continue;
  76065. }
  76066. currentPool.push(current);
  76067. // Find compatible meshes
  76068. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  76069. var otherMesh = globalPool[subIndex];
  76070. if (!this._canBeMerged(otherMesh)) {
  76071. continue;
  76072. }
  76073. if (otherMesh.material !== current.material) {
  76074. continue;
  76075. }
  76076. if (otherMesh.checkCollisions !== current.checkCollisions) {
  76077. continue;
  76078. }
  76079. currentPool.push(otherMesh);
  76080. globalLength--;
  76081. globalPool.splice(subIndex, 1);
  76082. subIndex--;
  76083. }
  76084. if (currentPool.length < 2) {
  76085. continue;
  76086. }
  76087. // Merge meshes
  76088. BABYLON.Mesh.MergeMeshes(currentPool);
  76089. }
  76090. if (updateSelectionTree != undefined) {
  76091. if (updateSelectionTree) {
  76092. scene.createOrUpdateSelectionOctree();
  76093. }
  76094. }
  76095. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  76096. scene.createOrUpdateSelectionOctree();
  76097. }
  76098. return true;
  76099. };
  76100. ;
  76101. MergeMeshesOptimization._UpdateSelectionTree = false;
  76102. return MergeMeshesOptimization;
  76103. }(SceneOptimization));
  76104. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  76105. /**
  76106. * Defines a list of options used by SceneOptimizer
  76107. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76108. */
  76109. var SceneOptimizerOptions = /** @class */ (function () {
  76110. /**
  76111. * Creates a new list of options used by SceneOptimizer
  76112. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  76113. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  76114. */
  76115. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  76116. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  76117. if (trackerDuration === void 0) { trackerDuration = 2000; }
  76118. this.targetFrameRate = targetFrameRate;
  76119. this.trackerDuration = trackerDuration;
  76120. /**
  76121. * Gets the list of optimizations to apply
  76122. */
  76123. this.optimizations = new Array();
  76124. }
  76125. /**
  76126. * Add a new optimization
  76127. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  76128. */
  76129. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  76130. this.optimizations.push(optimization);
  76131. return this;
  76132. };
  76133. /**
  76134. * Add a new custom optimization
  76135. * @param onApply defines the callback called to apply the custom optimization.
  76136. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  76137. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  76138. */
  76139. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  76140. if (priority === void 0) { priority = 0; }
  76141. var optimization = new CustomOptimization(priority);
  76142. optimization.onApply = onApply;
  76143. optimization.onGetDescription = onGetDescription;
  76144. this.optimizations.push(optimization);
  76145. return this;
  76146. };
  76147. /**
  76148. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  76149. * @param targetFrameRate defines the target frame rate (60 by default)
  76150. * @returns a SceneOptimizerOptions object
  76151. */
  76152. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  76153. var result = new SceneOptimizerOptions(targetFrameRate);
  76154. var priority = 0;
  76155. result.addOptimization(new MergeMeshesOptimization(priority));
  76156. result.addOptimization(new ShadowsOptimization(priority));
  76157. result.addOptimization(new LensFlaresOptimization(priority));
  76158. // Next priority
  76159. priority++;
  76160. result.addOptimization(new PostProcessesOptimization(priority));
  76161. result.addOptimization(new ParticlesOptimization(priority));
  76162. // Next priority
  76163. priority++;
  76164. result.addOptimization(new TextureOptimization(priority, 1024));
  76165. return result;
  76166. };
  76167. /**
  76168. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  76169. * @param targetFrameRate defines the target frame rate (60 by default)
  76170. * @returns a SceneOptimizerOptions object
  76171. */
  76172. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  76173. var result = new SceneOptimizerOptions(targetFrameRate);
  76174. var priority = 0;
  76175. result.addOptimization(new MergeMeshesOptimization(priority));
  76176. result.addOptimization(new ShadowsOptimization(priority));
  76177. result.addOptimization(new LensFlaresOptimization(priority));
  76178. // Next priority
  76179. priority++;
  76180. result.addOptimization(new PostProcessesOptimization(priority));
  76181. result.addOptimization(new ParticlesOptimization(priority));
  76182. // Next priority
  76183. priority++;
  76184. result.addOptimization(new TextureOptimization(priority, 512));
  76185. // Next priority
  76186. priority++;
  76187. result.addOptimization(new RenderTargetsOptimization(priority));
  76188. // Next priority
  76189. priority++;
  76190. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  76191. return result;
  76192. };
  76193. /**
  76194. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  76195. * @param targetFrameRate defines the target frame rate (60 by default)
  76196. * @returns a SceneOptimizerOptions object
  76197. */
  76198. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  76199. var result = new SceneOptimizerOptions(targetFrameRate);
  76200. var priority = 0;
  76201. result.addOptimization(new MergeMeshesOptimization(priority));
  76202. result.addOptimization(new ShadowsOptimization(priority));
  76203. result.addOptimization(new LensFlaresOptimization(priority));
  76204. // Next priority
  76205. priority++;
  76206. result.addOptimization(new PostProcessesOptimization(priority));
  76207. result.addOptimization(new ParticlesOptimization(priority));
  76208. // Next priority
  76209. priority++;
  76210. result.addOptimization(new TextureOptimization(priority, 256));
  76211. // Next priority
  76212. priority++;
  76213. result.addOptimization(new RenderTargetsOptimization(priority));
  76214. // Next priority
  76215. priority++;
  76216. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  76217. return result;
  76218. };
  76219. return SceneOptimizerOptions;
  76220. }());
  76221. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  76222. /**
  76223. * Class used to run optimizations in order to reach a target frame rate
  76224. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76225. */
  76226. var SceneOptimizer = /** @class */ (function () {
  76227. /**
  76228. * Creates a new SceneOptimizer
  76229. * @param scene defines the scene to work on
  76230. * @param options defines the options to use with the SceneOptimizer
  76231. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  76232. */
  76233. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  76234. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  76235. var _this = this;
  76236. this._isRunning = false;
  76237. this._currentPriorityLevel = 0;
  76238. this._targetFrameRate = 60;
  76239. this._trackerDuration = 2000;
  76240. this._currentFrameRate = 0;
  76241. /**
  76242. * Defines an observable called when the optimizer reaches the target frame rate
  76243. */
  76244. this.onSuccessObservable = new BABYLON.Observable();
  76245. /**
  76246. * Defines an observable called when the optimizer enables an optimization
  76247. */
  76248. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76249. /**
  76250. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76251. */
  76252. this.onFailureObservable = new BABYLON.Observable();
  76253. if (!options) {
  76254. this._options = new SceneOptimizerOptions();
  76255. }
  76256. else {
  76257. this._options = options;
  76258. }
  76259. if (this._options.targetFrameRate) {
  76260. this._targetFrameRate = this._options.targetFrameRate;
  76261. }
  76262. if (this._options.trackerDuration) {
  76263. this._trackerDuration = this._options.trackerDuration;
  76264. }
  76265. if (autoGeneratePriorities) {
  76266. var priority = 0;
  76267. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76268. var optim = _a[_i];
  76269. optim.priority = priority++;
  76270. }
  76271. }
  76272. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76273. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76274. _this._sceneDisposeObserver = null;
  76275. _this.dispose();
  76276. });
  76277. }
  76278. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76279. /**
  76280. * Gets the current priority level (0 at start)
  76281. */
  76282. get: function () {
  76283. return this._currentPriorityLevel;
  76284. },
  76285. enumerable: true,
  76286. configurable: true
  76287. });
  76288. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76289. /**
  76290. * Gets the current frame rate checked by the SceneOptimizer
  76291. */
  76292. get: function () {
  76293. return this._currentFrameRate;
  76294. },
  76295. enumerable: true,
  76296. configurable: true
  76297. });
  76298. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76299. /**
  76300. * Gets or sets the current target frame rate (60 by default)
  76301. */
  76302. get: function () {
  76303. return this._targetFrameRate;
  76304. },
  76305. /**
  76306. * Gets or sets the current target frame rate (60 by default)
  76307. */
  76308. set: function (value) {
  76309. this._targetFrameRate = value;
  76310. },
  76311. enumerable: true,
  76312. configurable: true
  76313. });
  76314. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76315. /**
  76316. * Gets or sets the current interval between two checks (every 2000ms by default)
  76317. */
  76318. get: function () {
  76319. return this._trackerDuration;
  76320. },
  76321. /**
  76322. * Gets or sets the current interval between two checks (every 2000ms by default)
  76323. */
  76324. set: function (value) {
  76325. this._trackerDuration = value;
  76326. },
  76327. enumerable: true,
  76328. configurable: true
  76329. });
  76330. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76331. /**
  76332. * Gets the list of active optimizations
  76333. */
  76334. get: function () {
  76335. return this._options.optimizations;
  76336. },
  76337. enumerable: true,
  76338. configurable: true
  76339. });
  76340. /**
  76341. * Stops the current optimizer
  76342. */
  76343. SceneOptimizer.prototype.stop = function () {
  76344. this._isRunning = false;
  76345. };
  76346. SceneOptimizer.prototype.reset = function () {
  76347. this._currentPriorityLevel = 0;
  76348. };
  76349. SceneOptimizer.prototype.start = function () {
  76350. var _this = this;
  76351. if (this._isRunning) {
  76352. return;
  76353. }
  76354. this._isRunning = true;
  76355. // Let's wait for the scene to be ready before running our check
  76356. this._scene.executeWhenReady(function () {
  76357. setTimeout(function () {
  76358. _this._checkCurrentState();
  76359. }, _this._trackerDuration);
  76360. });
  76361. };
  76362. SceneOptimizer.prototype._checkCurrentState = function () {
  76363. var _this = this;
  76364. if (!this._isRunning) {
  76365. return;
  76366. }
  76367. var scene = this._scene;
  76368. var options = this._options;
  76369. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76370. if (this._currentFrameRate >= this._targetFrameRate) {
  76371. this._isRunning = false;
  76372. this.onSuccessObservable.notifyObservers(this);
  76373. return;
  76374. }
  76375. // Apply current level of optimizations
  76376. var allDone = true;
  76377. var noOptimizationApplied = true;
  76378. for (var index = 0; index < options.optimizations.length; index++) {
  76379. var optimization = options.optimizations[index];
  76380. if (optimization.priority === this._currentPriorityLevel) {
  76381. noOptimizationApplied = false;
  76382. allDone = allDone && optimization.apply(scene);
  76383. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76384. }
  76385. }
  76386. // If no optimization was applied, this is a failure :(
  76387. if (noOptimizationApplied) {
  76388. this._isRunning = false;
  76389. this.onFailureObservable.notifyObservers(this);
  76390. return;
  76391. }
  76392. // If all optimizations were done, move to next level
  76393. if (allDone) {
  76394. this._currentPriorityLevel++;
  76395. }
  76396. // Let's the system running for a specific amount of time before checking FPS
  76397. scene.executeWhenReady(function () {
  76398. setTimeout(function () {
  76399. _this._checkCurrentState();
  76400. }, _this._trackerDuration);
  76401. });
  76402. };
  76403. /**
  76404. * Release all resources
  76405. */
  76406. SceneOptimizer.prototype.dispose = function () {
  76407. this.stop();
  76408. this.onSuccessObservable.clear();
  76409. this.onFailureObservable.clear();
  76410. this.onNewOptimizationAppliedObservable.clear();
  76411. if (this._sceneDisposeObserver) {
  76412. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76413. }
  76414. };
  76415. /**
  76416. * Helper function to create a SceneOptimizer with one single line of code
  76417. * @param scene defines the scene to work on
  76418. * @param options defines the options to use with the SceneOptimizer
  76419. * @param onSuccess defines a callback to call on success
  76420. * @param onFailure defines a callback to call on failure
  76421. */
  76422. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76423. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76424. if (onSuccess) {
  76425. optimizer.onSuccessObservable.add(function () {
  76426. onSuccess();
  76427. });
  76428. }
  76429. if (onFailure) {
  76430. optimizer.onFailureObservable.add(function () {
  76431. onFailure();
  76432. });
  76433. }
  76434. optimizer.start();
  76435. return optimizer;
  76436. };
  76437. return SceneOptimizer;
  76438. }());
  76439. BABYLON.SceneOptimizer = SceneOptimizer;
  76440. })(BABYLON || (BABYLON = {}));
  76441. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76442. var BABYLON;
  76443. (function (BABYLON) {
  76444. var OutlineRenderer = /** @class */ (function () {
  76445. function OutlineRenderer(scene) {
  76446. this.zOffset = 1;
  76447. this._scene = scene;
  76448. }
  76449. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76450. var _this = this;
  76451. if (useOverlay === void 0) { useOverlay = false; }
  76452. var scene = this._scene;
  76453. var engine = this._scene.getEngine();
  76454. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76455. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76456. return;
  76457. }
  76458. var mesh = subMesh.getRenderingMesh();
  76459. var material = subMesh.getMaterial();
  76460. if (!material || !scene.activeCamera) {
  76461. return;
  76462. }
  76463. engine.enableEffect(this._effect);
  76464. // Logarithmic depth
  76465. if (material.useLogarithmicDepth) {
  76466. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76467. }
  76468. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76469. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76470. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76471. // Bones
  76472. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76473. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76474. }
  76475. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76476. // Alpha test
  76477. if (material && material.needAlphaTesting()) {
  76478. var alphaTexture = material.getAlphaTestTexture();
  76479. if (alphaTexture) {
  76480. this._effect.setTexture("diffuseSampler", alphaTexture);
  76481. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76482. }
  76483. }
  76484. engine.setZOffset(-this.zOffset);
  76485. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76486. engine.setZOffset(0);
  76487. };
  76488. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76489. var defines = [];
  76490. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76491. var mesh = subMesh.getMesh();
  76492. var material = subMesh.getMaterial();
  76493. if (material) {
  76494. // Alpha test
  76495. if (material.needAlphaTesting()) {
  76496. defines.push("#define ALPHATEST");
  76497. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76498. attribs.push(BABYLON.VertexBuffer.UVKind);
  76499. defines.push("#define UV1");
  76500. }
  76501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76502. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76503. defines.push("#define UV2");
  76504. }
  76505. }
  76506. //Logarithmic depth
  76507. if (material.useLogarithmicDepth) {
  76508. defines.push("#define LOGARITHMICDEPTH");
  76509. }
  76510. }
  76511. // Bones
  76512. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76513. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76514. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76515. if (mesh.numBoneInfluencers > 4) {
  76516. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76517. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76518. }
  76519. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76520. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76521. }
  76522. else {
  76523. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76524. }
  76525. // Instances
  76526. if (useInstances) {
  76527. defines.push("#define INSTANCES");
  76528. attribs.push("world0");
  76529. attribs.push("world1");
  76530. attribs.push("world2");
  76531. attribs.push("world3");
  76532. }
  76533. // Get correct effect
  76534. var join = defines.join("\n");
  76535. if (this._cachedDefines !== join) {
  76536. this._cachedDefines = join;
  76537. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76538. }
  76539. return this._effect.isReady();
  76540. };
  76541. return OutlineRenderer;
  76542. }());
  76543. BABYLON.OutlineRenderer = OutlineRenderer;
  76544. })(BABYLON || (BABYLON = {}));
  76545. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76546. var BABYLON;
  76547. (function (BABYLON) {
  76548. var FaceAdjacencies = /** @class */ (function () {
  76549. function FaceAdjacencies() {
  76550. this.edges = new Array();
  76551. this.edgesConnectedCount = 0;
  76552. }
  76553. return FaceAdjacencies;
  76554. }());
  76555. var EdgesRenderer = /** @class */ (function () {
  76556. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76557. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76558. if (epsilon === void 0) { epsilon = 0.95; }
  76559. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76560. this.edgesWidthScalerForOrthographic = 1000.0;
  76561. this.edgesWidthScalerForPerspective = 50.0;
  76562. this._linesPositions = new Array();
  76563. this._linesNormals = new Array();
  76564. this._linesIndices = new Array();
  76565. this._buffers = {};
  76566. this._checkVerticesInsteadOfIndices = false;
  76567. this._source = source;
  76568. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76569. this._epsilon = epsilon;
  76570. this._prepareRessources();
  76571. this._generateEdgesLines();
  76572. }
  76573. EdgesRenderer.prototype._prepareRessources = function () {
  76574. if (this._lineShader) {
  76575. return;
  76576. }
  76577. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76578. attributes: ["position", "normal"],
  76579. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76580. });
  76581. this._lineShader.disableDepthWrite = true;
  76582. this._lineShader.backFaceCulling = false;
  76583. };
  76584. EdgesRenderer.prototype._rebuild = function () {
  76585. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76586. if (buffer) {
  76587. buffer._rebuild();
  76588. }
  76589. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76590. if (buffer) {
  76591. buffer._rebuild();
  76592. }
  76593. var scene = this._source.getScene();
  76594. var engine = scene.getEngine();
  76595. this._ib = engine.createIndexBuffer(this._linesIndices);
  76596. };
  76597. EdgesRenderer.prototype.dispose = function () {
  76598. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76599. if (buffer) {
  76600. buffer.dispose();
  76601. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76602. }
  76603. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76604. if (buffer) {
  76605. buffer.dispose();
  76606. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76607. }
  76608. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76609. this._lineShader.dispose();
  76610. };
  76611. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76612. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76613. return 0;
  76614. }
  76615. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76616. return 1;
  76617. }
  76618. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76619. return 2;
  76620. }
  76621. return -1;
  76622. };
  76623. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76624. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76625. return 0;
  76626. }
  76627. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76628. return 1;
  76629. }
  76630. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76631. return 2;
  76632. }
  76633. return -1;
  76634. };
  76635. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76636. var needToCreateLine;
  76637. if (edge === undefined) {
  76638. needToCreateLine = true;
  76639. }
  76640. else {
  76641. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76642. needToCreateLine = dotProduct < this._epsilon;
  76643. }
  76644. if (needToCreateLine) {
  76645. var offset = this._linesPositions.length / 3;
  76646. var normal = p0.subtract(p1);
  76647. normal.normalize();
  76648. // Positions
  76649. this._linesPositions.push(p0.x);
  76650. this._linesPositions.push(p0.y);
  76651. this._linesPositions.push(p0.z);
  76652. this._linesPositions.push(p0.x);
  76653. this._linesPositions.push(p0.y);
  76654. this._linesPositions.push(p0.z);
  76655. this._linesPositions.push(p1.x);
  76656. this._linesPositions.push(p1.y);
  76657. this._linesPositions.push(p1.z);
  76658. this._linesPositions.push(p1.x);
  76659. this._linesPositions.push(p1.y);
  76660. this._linesPositions.push(p1.z);
  76661. // Normals
  76662. this._linesNormals.push(p1.x);
  76663. this._linesNormals.push(p1.y);
  76664. this._linesNormals.push(p1.z);
  76665. this._linesNormals.push(-1);
  76666. this._linesNormals.push(p1.x);
  76667. this._linesNormals.push(p1.y);
  76668. this._linesNormals.push(p1.z);
  76669. this._linesNormals.push(1);
  76670. this._linesNormals.push(p0.x);
  76671. this._linesNormals.push(p0.y);
  76672. this._linesNormals.push(p0.z);
  76673. this._linesNormals.push(-1);
  76674. this._linesNormals.push(p0.x);
  76675. this._linesNormals.push(p0.y);
  76676. this._linesNormals.push(p0.z);
  76677. this._linesNormals.push(1);
  76678. // Indices
  76679. this._linesIndices.push(offset);
  76680. this._linesIndices.push(offset + 1);
  76681. this._linesIndices.push(offset + 2);
  76682. this._linesIndices.push(offset);
  76683. this._linesIndices.push(offset + 2);
  76684. this._linesIndices.push(offset + 3);
  76685. }
  76686. };
  76687. EdgesRenderer.prototype._generateEdgesLines = function () {
  76688. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76689. var indices = this._source.getIndices();
  76690. if (!indices || !positions) {
  76691. return;
  76692. }
  76693. // First let's find adjacencies
  76694. var adjacencies = new Array();
  76695. var faceNormals = new Array();
  76696. var index;
  76697. var faceAdjacencies;
  76698. // Prepare faces
  76699. for (index = 0; index < indices.length; index += 3) {
  76700. faceAdjacencies = new FaceAdjacencies();
  76701. var p0Index = indices[index];
  76702. var p1Index = indices[index + 1];
  76703. var p2Index = indices[index + 2];
  76704. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76705. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76706. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76707. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76708. faceNormal.normalize();
  76709. faceNormals.push(faceNormal);
  76710. adjacencies.push(faceAdjacencies);
  76711. }
  76712. // Scan
  76713. for (index = 0; index < adjacencies.length; index++) {
  76714. faceAdjacencies = adjacencies[index];
  76715. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76716. var otherFaceAdjacencies = adjacencies[otherIndex];
  76717. if (faceAdjacencies.edgesConnectedCount === 3) {
  76718. break;
  76719. }
  76720. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76721. continue;
  76722. }
  76723. var otherP0 = indices[otherIndex * 3];
  76724. var otherP1 = indices[otherIndex * 3 + 1];
  76725. var otherP2 = indices[otherIndex * 3 + 2];
  76726. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76727. var otherEdgeIndex = 0;
  76728. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76729. continue;
  76730. }
  76731. switch (edgeIndex) {
  76732. case 0:
  76733. if (this._checkVerticesInsteadOfIndices) {
  76734. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76735. }
  76736. else {
  76737. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76738. }
  76739. break;
  76740. case 1:
  76741. if (this._checkVerticesInsteadOfIndices) {
  76742. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76743. }
  76744. else {
  76745. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76746. }
  76747. break;
  76748. case 2:
  76749. if (this._checkVerticesInsteadOfIndices) {
  76750. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76751. }
  76752. else {
  76753. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76754. }
  76755. break;
  76756. }
  76757. if (otherEdgeIndex === -1) {
  76758. continue;
  76759. }
  76760. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76761. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76762. faceAdjacencies.edgesConnectedCount++;
  76763. otherFaceAdjacencies.edgesConnectedCount++;
  76764. if (faceAdjacencies.edgesConnectedCount === 3) {
  76765. break;
  76766. }
  76767. }
  76768. }
  76769. }
  76770. // Create lines
  76771. for (index = 0; index < adjacencies.length; index++) {
  76772. // 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
  76773. var current = adjacencies[index];
  76774. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76775. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76776. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76777. }
  76778. // Merge into a single mesh
  76779. var engine = this._source.getScene().getEngine();
  76780. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76781. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76782. this._ib = engine.createIndexBuffer(this._linesIndices);
  76783. this._indicesCount = this._linesIndices.length;
  76784. };
  76785. EdgesRenderer.prototype.render = function () {
  76786. var scene = this._source.getScene();
  76787. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76788. return;
  76789. }
  76790. var engine = scene.getEngine();
  76791. this._lineShader._preBind();
  76792. // VBOs
  76793. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76794. scene.resetCachedMaterial();
  76795. this._lineShader.setColor4("color", this._source.edgesColor);
  76796. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76797. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76798. }
  76799. else {
  76800. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76801. }
  76802. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76803. this._lineShader.bind(this._source.getWorldMatrix());
  76804. // Draw order
  76805. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76806. this._lineShader.unbind();
  76807. engine.setDepthWrite(true);
  76808. };
  76809. return EdgesRenderer;
  76810. }());
  76811. BABYLON.EdgesRenderer = EdgesRenderer;
  76812. })(BABYLON || (BABYLON = {}));
  76813. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76814. var BABYLON;
  76815. (function (BABYLON) {
  76816. /**
  76817. * Special Glow Blur post process only blurring the alpha channel
  76818. * It enforces keeping the most luminous color in the color channel.
  76819. */
  76820. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76821. __extends(GlowBlurPostProcess, _super);
  76822. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76824. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76825. _this.direction = direction;
  76826. _this.kernel = kernel;
  76827. _this.onApplyObservable.add(function (effect) {
  76828. effect.setFloat2("screenSize", _this.width, _this.height);
  76829. effect.setVector2("direction", _this.direction);
  76830. effect.setFloat("blurWidth", _this.kernel);
  76831. });
  76832. return _this;
  76833. }
  76834. return GlowBlurPostProcess;
  76835. }(BABYLON.PostProcess));
  76836. /**
  76837. * The highlight layer Helps adding a glow effect around a mesh.
  76838. *
  76839. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76840. * glowy meshes to your scene.
  76841. *
  76842. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76843. */
  76844. var HighlightLayer = /** @class */ (function () {
  76845. /**
  76846. * Instantiates a new highlight Layer and references it to the scene..
  76847. * @param name The name of the layer
  76848. * @param scene The scene to use the layer in
  76849. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76850. */
  76851. function HighlightLayer(name, scene, options) {
  76852. this.name = name;
  76853. this._vertexBuffers = {};
  76854. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76855. this._meshes = {};
  76856. this._maxSize = 0;
  76857. this._shouldRender = false;
  76858. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76859. this._excludedMeshes = {};
  76860. /**
  76861. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76862. */
  76863. this.innerGlow = true;
  76864. /**
  76865. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76866. */
  76867. this.outerGlow = true;
  76868. /**
  76869. * Specifies wether the highlight layer is enabled or not.
  76870. */
  76871. this.isEnabled = true;
  76872. /**
  76873. * An event triggered when the highlight layer has been disposed.
  76874. * @type {BABYLON.Observable}
  76875. */
  76876. this.onDisposeObservable = new BABYLON.Observable();
  76877. /**
  76878. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76879. * @type {BABYLON.Observable}
  76880. */
  76881. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76882. /**
  76883. * An event triggered when the highlight layer is being blurred.
  76884. * @type {BABYLON.Observable}
  76885. */
  76886. this.onBeforeBlurObservable = new BABYLON.Observable();
  76887. /**
  76888. * An event triggered when the highlight layer has been blurred.
  76889. * @type {BABYLON.Observable}
  76890. */
  76891. this.onAfterBlurObservable = new BABYLON.Observable();
  76892. /**
  76893. * An event triggered when the glowing blurred texture is being merged in the scene.
  76894. * @type {BABYLON.Observable}
  76895. */
  76896. this.onBeforeComposeObservable = new BABYLON.Observable();
  76897. /**
  76898. * An event triggered when the glowing blurred texture has been merged in the scene.
  76899. * @type {BABYLON.Observable}
  76900. */
  76901. this.onAfterComposeObservable = new BABYLON.Observable();
  76902. /**
  76903. * An event triggered when the highlight layer changes its size.
  76904. * @type {BABYLON.Observable}
  76905. */
  76906. this.onSizeChangedObservable = new BABYLON.Observable();
  76907. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76908. var engine = scene.getEngine();
  76909. this._engine = engine;
  76910. this._maxSize = this._engine.getCaps().maxTextureSize;
  76911. this._scene.highlightLayers.push(this);
  76912. // Warn on stencil.
  76913. if (!this._engine.isStencilEnable) {
  76914. 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 }");
  76915. }
  76916. // Adapt options
  76917. this._options = options || {
  76918. mainTextureRatio: 0.5,
  76919. blurTextureSizeRatio: 0.5,
  76920. blurHorizontalSize: 1.0,
  76921. blurVerticalSize: 1.0,
  76922. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76923. camera: null
  76924. };
  76925. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76926. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76927. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76928. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76929. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76930. // VBO
  76931. var vertices = [];
  76932. vertices.push(1, 1);
  76933. vertices.push(-1, 1);
  76934. vertices.push(-1, -1);
  76935. vertices.push(1, -1);
  76936. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76937. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76938. this._createIndexBuffer();
  76939. // Effect
  76940. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76941. // Render target
  76942. this.setMainTextureSize();
  76943. // Create Textures and post processes
  76944. this.createTextureAndPostProcesses();
  76945. }
  76946. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76947. /**
  76948. * Gets the horizontal size of the blur.
  76949. */
  76950. get: function () {
  76951. return this._horizontalBlurPostprocess.kernel;
  76952. },
  76953. /**
  76954. * Specifies the horizontal size of the blur.
  76955. */
  76956. set: function (value) {
  76957. this._horizontalBlurPostprocess.kernel = value;
  76958. },
  76959. enumerable: true,
  76960. configurable: true
  76961. });
  76962. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76963. /**
  76964. * Gets the vertical size of the blur.
  76965. */
  76966. get: function () {
  76967. return this._verticalBlurPostprocess.kernel;
  76968. },
  76969. /**
  76970. * Specifies the vertical size of the blur.
  76971. */
  76972. set: function (value) {
  76973. this._verticalBlurPostprocess.kernel = value;
  76974. },
  76975. enumerable: true,
  76976. configurable: true
  76977. });
  76978. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76979. /**
  76980. * Gets the camera attached to the layer.
  76981. */
  76982. get: function () {
  76983. return this._options.camera;
  76984. },
  76985. enumerable: true,
  76986. configurable: true
  76987. });
  76988. HighlightLayer.prototype._createIndexBuffer = function () {
  76989. var engine = this._scene.getEngine();
  76990. // Indices
  76991. var indices = [];
  76992. indices.push(0);
  76993. indices.push(1);
  76994. indices.push(2);
  76995. indices.push(0);
  76996. indices.push(2);
  76997. indices.push(3);
  76998. this._indexBuffer = engine.createIndexBuffer(indices);
  76999. };
  77000. HighlightLayer.prototype._rebuild = function () {
  77001. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77002. if (vb) {
  77003. vb._rebuild();
  77004. }
  77005. this._createIndexBuffer();
  77006. };
  77007. /**
  77008. * Creates the render target textures and post processes used in the highlight layer.
  77009. */
  77010. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  77011. var _this = this;
  77012. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  77013. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  77014. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  77015. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  77016. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  77017. width: this._mainTextureDesiredSize.width,
  77018. height: this._mainTextureDesiredSize.height
  77019. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77020. this._mainTexture.activeCamera = this._options.camera;
  77021. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77022. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77023. this._mainTexture.anisotropicFilteringLevel = 1;
  77024. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77025. this._mainTexture.renderParticles = false;
  77026. this._mainTexture.renderList = null;
  77027. this._mainTexture.ignoreCameraViewport = true;
  77028. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  77029. width: blurTextureWidth,
  77030. height: blurTextureHeight
  77031. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77032. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77033. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77034. this._blurTexture.anisotropicFilteringLevel = 16;
  77035. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77036. this._blurTexture.renderParticles = false;
  77037. this._blurTexture.ignoreCameraViewport = true;
  77038. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77039. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  77040. effect.setTexture("textureSampler", _this._mainTexture);
  77041. });
  77042. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  77043. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77044. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  77045. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77046. });
  77047. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77048. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  77049. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77050. });
  77051. }
  77052. else {
  77053. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77054. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  77055. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77056. });
  77057. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  77058. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  77059. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  77060. });
  77061. }
  77062. this._mainTexture.onAfterUnbindObservable.add(function () {
  77063. _this.onBeforeBlurObservable.notifyObservers(_this);
  77064. var internalTexture = _this._blurTexture.getInternalTexture();
  77065. if (internalTexture) {
  77066. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  77067. }
  77068. _this.onAfterBlurObservable.notifyObservers(_this);
  77069. });
  77070. // Custom render function
  77071. var renderSubMesh = function (subMesh) {
  77072. if (!_this._meshes) {
  77073. return;
  77074. }
  77075. var material = subMesh.getMaterial();
  77076. var mesh = subMesh.getRenderingMesh();
  77077. var scene = _this._scene;
  77078. var engine = scene.getEngine();
  77079. if (!material) {
  77080. return;
  77081. }
  77082. // Do not block in blend mode.
  77083. if (material.needAlphaBlendingForMesh(mesh)) {
  77084. return;
  77085. }
  77086. // Culling
  77087. engine.setState(material.backFaceCulling);
  77088. // Managing instances
  77089. var batch = mesh._getInstancesRenderList(subMesh._id);
  77090. if (batch.mustReturn) {
  77091. return;
  77092. }
  77093. // Excluded Mesh
  77094. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77095. return;
  77096. }
  77097. ;
  77098. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77099. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  77100. var emissiveTexture = null;
  77101. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  77102. emissiveTexture = material.emissiveTexture;
  77103. }
  77104. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  77105. engine.enableEffect(_this._glowMapGenerationEffect);
  77106. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  77107. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  77108. if (highlightLayerMesh) {
  77109. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  77110. }
  77111. else {
  77112. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  77113. }
  77114. // Alpha test
  77115. if (material && material.needAlphaTesting()) {
  77116. var alphaTexture = material.getAlphaTestTexture();
  77117. if (alphaTexture) {
  77118. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  77119. var textureMatrix = alphaTexture.getTextureMatrix();
  77120. if (textureMatrix) {
  77121. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  77122. }
  77123. }
  77124. }
  77125. // Glow emissive only
  77126. if (emissiveTexture) {
  77127. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  77128. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  77129. }
  77130. // Bones
  77131. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77132. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77133. }
  77134. // Draw
  77135. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  77136. }
  77137. else {
  77138. // Need to reset refresh rate of the shadowMap
  77139. _this._mainTexture.resetRefreshCounter();
  77140. }
  77141. };
  77142. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77143. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  77144. var index;
  77145. var engine = _this._scene.getEngine();
  77146. if (depthOnlySubMeshes.length) {
  77147. engine.setColorWrite(false);
  77148. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77149. renderSubMesh(depthOnlySubMeshes.data[index]);
  77150. }
  77151. engine.setColorWrite(true);
  77152. }
  77153. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77154. renderSubMesh(opaqueSubMeshes.data[index]);
  77155. }
  77156. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77157. renderSubMesh(alphaTestSubMeshes.data[index]);
  77158. }
  77159. for (index = 0; index < transparentSubMeshes.length; index++) {
  77160. renderSubMesh(transparentSubMeshes.data[index]);
  77161. }
  77162. };
  77163. this._mainTexture.onClearObservable.add(function (engine) {
  77164. engine.clear(HighlightLayer.neutralColor, true, true, true);
  77165. });
  77166. };
  77167. /**
  77168. * Checks for the readiness of the element composing the layer.
  77169. * @param subMesh the mesh to check for
  77170. * @param useInstances specify wether or not to use instances to render the mesh
  77171. * @param emissiveTexture the associated emissive texture used to generate the glow
  77172. * @return true if ready otherwise, false
  77173. */
  77174. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  77175. var material = subMesh.getMaterial();
  77176. var mesh = subMesh.getRenderingMesh();
  77177. if (!material || !mesh || !this._meshes) {
  77178. return false;
  77179. }
  77180. var emissiveTexture = null;
  77181. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  77182. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  77183. emissiveTexture = material.emissiveTexture;
  77184. }
  77185. return this._isReady(subMesh, useInstances, emissiveTexture);
  77186. };
  77187. /**
  77188. * Checks for the readiness of the element composing the layer.
  77189. * @param subMesh the mesh to check for
  77190. * @param useInstances specify wether or not to use instances to render the mesh
  77191. * @param emissiveTexture the associated emissive texture used to generate the glow
  77192. * @return true if ready otherwise, false
  77193. */
  77194. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  77195. var material = subMesh.getMaterial();
  77196. if (!material) {
  77197. return false;
  77198. }
  77199. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  77200. return false;
  77201. }
  77202. var defines = [];
  77203. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77204. var mesh = subMesh.getMesh();
  77205. var uv1 = false;
  77206. var uv2 = false;
  77207. // Alpha test
  77208. if (material && material.needAlphaTesting()) {
  77209. var alphaTexture = material.getAlphaTestTexture();
  77210. if (alphaTexture) {
  77211. defines.push("#define ALPHATEST");
  77212. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77213. alphaTexture.coordinatesIndex === 1) {
  77214. defines.push("#define DIFFUSEUV2");
  77215. uv2 = true;
  77216. }
  77217. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77218. defines.push("#define DIFFUSEUV1");
  77219. uv1 = true;
  77220. }
  77221. }
  77222. }
  77223. // Emissive
  77224. if (emissiveTexture) {
  77225. defines.push("#define EMISSIVE");
  77226. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77227. emissiveTexture.coordinatesIndex === 1) {
  77228. defines.push("#define EMISSIVEUV2");
  77229. uv2 = true;
  77230. }
  77231. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77232. defines.push("#define EMISSIVEUV1");
  77233. uv1 = true;
  77234. }
  77235. }
  77236. if (uv1) {
  77237. attribs.push(BABYLON.VertexBuffer.UVKind);
  77238. defines.push("#define UV1");
  77239. }
  77240. if (uv2) {
  77241. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77242. defines.push("#define UV2");
  77243. }
  77244. // Bones
  77245. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77248. if (mesh.numBoneInfluencers > 4) {
  77249. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77250. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77251. }
  77252. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77253. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77254. }
  77255. else {
  77256. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77257. }
  77258. // Instances
  77259. if (useInstances) {
  77260. defines.push("#define INSTANCES");
  77261. attribs.push("world0");
  77262. attribs.push("world1");
  77263. attribs.push("world2");
  77264. attribs.push("world3");
  77265. }
  77266. // Get correct effect
  77267. var join = defines.join("\n");
  77268. if (this._cachedDefines !== join) {
  77269. this._cachedDefines = join;
  77270. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77271. }
  77272. return this._glowMapGenerationEffect.isReady();
  77273. };
  77274. /**
  77275. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77276. */
  77277. HighlightLayer.prototype.render = function () {
  77278. var currentEffect = this._glowMapMergeEffect;
  77279. // Check
  77280. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77281. return;
  77282. var engine = this._scene.getEngine();
  77283. this.onBeforeComposeObservable.notifyObservers(this);
  77284. // Render
  77285. engine.enableEffect(currentEffect);
  77286. engine.setState(false);
  77287. // Cache
  77288. var previousStencilBuffer = engine.getStencilBuffer();
  77289. var previousStencilFunction = engine.getStencilFunction();
  77290. var previousStencilMask = engine.getStencilMask();
  77291. var previousStencilOperationPass = engine.getStencilOperationPass();
  77292. var previousStencilOperationFail = engine.getStencilOperationFail();
  77293. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77294. var previousAlphaMode = engine.getAlphaMode();
  77295. // Texture
  77296. currentEffect.setTexture("textureSampler", this._blurTexture);
  77297. // VBOs
  77298. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77299. // Stencil operations
  77300. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77301. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77302. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77303. // Draw order
  77304. engine.setAlphaMode(this._options.alphaBlendingMode);
  77305. engine.setStencilMask(0x00);
  77306. engine.setStencilBuffer(true);
  77307. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77308. if (this.outerGlow) {
  77309. currentEffect.setFloat("offset", 0);
  77310. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77311. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77312. }
  77313. if (this.innerGlow) {
  77314. currentEffect.setFloat("offset", 1);
  77315. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77316. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77317. }
  77318. // Restore Cache
  77319. engine.setStencilFunction(previousStencilFunction);
  77320. engine.setStencilMask(previousStencilMask);
  77321. engine.setAlphaMode(previousAlphaMode);
  77322. engine.setStencilBuffer(previousStencilBuffer);
  77323. engine.setStencilOperationPass(previousStencilOperationPass);
  77324. engine.setStencilOperationFail(previousStencilOperationFail);
  77325. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77326. engine._stencilState.reset();
  77327. this.onAfterComposeObservable.notifyObservers(this);
  77328. // Handle size changes.
  77329. var size = this._mainTexture.getSize();
  77330. this.setMainTextureSize();
  77331. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77332. // Recreate RTT and post processes on size change.
  77333. this.onSizeChangedObservable.notifyObservers(this);
  77334. this.disposeTextureAndPostProcesses();
  77335. this.createTextureAndPostProcesses();
  77336. }
  77337. };
  77338. /**
  77339. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77340. * @param mesh The mesh to exclude from the highlight layer
  77341. */
  77342. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77343. if (!this._excludedMeshes) {
  77344. return;
  77345. }
  77346. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77347. if (!meshExcluded) {
  77348. this._excludedMeshes[mesh.uniqueId] = {
  77349. mesh: mesh,
  77350. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77351. mesh.getEngine().setStencilBuffer(false);
  77352. }),
  77353. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77354. mesh.getEngine().setStencilBuffer(true);
  77355. }),
  77356. };
  77357. }
  77358. };
  77359. /**
  77360. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77361. * @param mesh The mesh to highlight
  77362. */
  77363. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77364. if (!this._excludedMeshes) {
  77365. return;
  77366. }
  77367. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77368. if (meshExcluded) {
  77369. if (meshExcluded.beforeRender) {
  77370. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77371. }
  77372. if (meshExcluded.afterRender) {
  77373. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77374. }
  77375. }
  77376. this._excludedMeshes[mesh.uniqueId] = null;
  77377. };
  77378. /**
  77379. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77380. * @param mesh mesh to test
  77381. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77382. */
  77383. HighlightLayer.prototype.hasMesh = function (mesh) {
  77384. if (!this._meshes) {
  77385. return false;
  77386. }
  77387. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77388. };
  77389. /**
  77390. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77391. * @param mesh The mesh to highlight
  77392. * @param color The color of the highlight
  77393. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77394. */
  77395. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77396. var _this = this;
  77397. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77398. if (!this._meshes) {
  77399. return;
  77400. }
  77401. var meshHighlight = this._meshes[mesh.uniqueId];
  77402. if (meshHighlight) {
  77403. meshHighlight.color = color;
  77404. }
  77405. else {
  77406. this._meshes[mesh.uniqueId] = {
  77407. mesh: mesh,
  77408. color: color,
  77409. // Lambda required for capture due to Observable this context
  77410. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77411. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77412. _this.defaultStencilReference(mesh);
  77413. }
  77414. else {
  77415. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77416. }
  77417. }),
  77418. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77419. glowEmissiveOnly: glowEmissiveOnly
  77420. };
  77421. }
  77422. this._shouldRender = true;
  77423. };
  77424. /**
  77425. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77426. * @param mesh The mesh to highlight
  77427. */
  77428. HighlightLayer.prototype.removeMesh = function (mesh) {
  77429. if (!this._meshes) {
  77430. return;
  77431. }
  77432. var meshHighlight = this._meshes[mesh.uniqueId];
  77433. if (meshHighlight) {
  77434. if (meshHighlight.observerHighlight) {
  77435. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77436. }
  77437. if (meshHighlight.observerDefault) {
  77438. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77439. }
  77440. delete this._meshes[mesh.uniqueId];
  77441. }
  77442. this._shouldRender = false;
  77443. for (var meshHighlightToCheck in this._meshes) {
  77444. if (this._meshes[meshHighlightToCheck]) {
  77445. this._shouldRender = true;
  77446. break;
  77447. }
  77448. }
  77449. };
  77450. /**
  77451. * Returns true if the layer contains information to display, otherwise false.
  77452. */
  77453. HighlightLayer.prototype.shouldRender = function () {
  77454. return this.isEnabled && this._shouldRender;
  77455. };
  77456. /**
  77457. * Sets the main texture desired size which is the closest power of two
  77458. * of the engine canvas size.
  77459. */
  77460. HighlightLayer.prototype.setMainTextureSize = function () {
  77461. if (this._options.mainTextureFixedSize) {
  77462. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77463. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77464. }
  77465. else {
  77466. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77467. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77468. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77469. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77470. }
  77471. };
  77472. /**
  77473. * Force the stencil to the normal expected value for none glowing parts
  77474. */
  77475. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77476. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77477. };
  77478. /**
  77479. * Dispose only the render target textures and post process.
  77480. */
  77481. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77482. this._blurTexture.dispose();
  77483. this._mainTexture.dispose();
  77484. this._downSamplePostprocess.dispose();
  77485. this._horizontalBlurPostprocess.dispose();
  77486. this._verticalBlurPostprocess.dispose();
  77487. };
  77488. /**
  77489. * Dispose the highlight layer and free resources.
  77490. */
  77491. HighlightLayer.prototype.dispose = function () {
  77492. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77493. if (vertexBuffer) {
  77494. vertexBuffer.dispose();
  77495. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77496. }
  77497. if (this._indexBuffer) {
  77498. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77499. this._indexBuffer = null;
  77500. }
  77501. // Clean textures and post processes
  77502. this.disposeTextureAndPostProcesses();
  77503. if (this._meshes) {
  77504. // Clean mesh references
  77505. for (var id in this._meshes) {
  77506. var meshHighlight = this._meshes[id];
  77507. if (meshHighlight && meshHighlight.mesh) {
  77508. if (meshHighlight.observerHighlight) {
  77509. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77510. }
  77511. if (meshHighlight.observerDefault) {
  77512. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77513. }
  77514. }
  77515. }
  77516. this._meshes = null;
  77517. }
  77518. if (this._excludedMeshes) {
  77519. for (var id in this._excludedMeshes) {
  77520. var meshHighlight = this._excludedMeshes[id];
  77521. if (meshHighlight) {
  77522. if (meshHighlight.beforeRender) {
  77523. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77524. }
  77525. if (meshHighlight.afterRender) {
  77526. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77527. }
  77528. }
  77529. }
  77530. this._excludedMeshes = null;
  77531. }
  77532. // Remove from scene
  77533. var index = this._scene.highlightLayers.indexOf(this, 0);
  77534. if (index > -1) {
  77535. this._scene.highlightLayers.splice(index, 1);
  77536. }
  77537. // Callback
  77538. this.onDisposeObservable.notifyObservers(this);
  77539. this.onDisposeObservable.clear();
  77540. this.onBeforeRenderMainTextureObservable.clear();
  77541. this.onBeforeBlurObservable.clear();
  77542. this.onBeforeComposeObservable.clear();
  77543. this.onAfterComposeObservable.clear();
  77544. this.onSizeChangedObservable.clear();
  77545. };
  77546. /**
  77547. * The neutral color used during the preparation of the glow effect.
  77548. * This is black by default as the blend operation is a blend operation.
  77549. */
  77550. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77551. /**
  77552. * Stencil value used for glowing meshes.
  77553. */
  77554. HighlightLayer.glowingMeshStencilReference = 0x02;
  77555. /**
  77556. * Stencil value used for the other meshes in the scene.
  77557. */
  77558. HighlightLayer.normalMeshStencilReference = 0x01;
  77559. return HighlightLayer;
  77560. }());
  77561. BABYLON.HighlightLayer = HighlightLayer;
  77562. })(BABYLON || (BABYLON = {}));
  77563. //# sourceMappingURL=babylon.highlightlayer.js.map
  77564. var BABYLON;
  77565. (function (BABYLON) {
  77566. var AssetTaskState;
  77567. (function (AssetTaskState) {
  77568. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77569. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77570. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77571. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77572. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77573. var AbstractAssetTask = /** @class */ (function () {
  77574. function AbstractAssetTask(name) {
  77575. this.name = name;
  77576. this.isCompleted = false;
  77577. this.taskState = AssetTaskState.INIT;
  77578. }
  77579. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77580. var _this = this;
  77581. this.taskState = AssetTaskState.RUNNING;
  77582. this.runTask(scene, function () {
  77583. _this.onDoneCallback(onSuccess, onError);
  77584. }, function (msg, exception) {
  77585. _this.onErrorCallback(onError, msg, exception);
  77586. });
  77587. };
  77588. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77589. throw new Error("runTask is not implemented");
  77590. };
  77591. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77592. this.taskState = AssetTaskState.ERROR;
  77593. this.errorObject = {
  77594. message: message,
  77595. exception: exception
  77596. };
  77597. if (this.onError) {
  77598. this.onError(this, message, exception);
  77599. }
  77600. onError();
  77601. };
  77602. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77603. try {
  77604. this.taskState = AssetTaskState.DONE;
  77605. this.isCompleted = true;
  77606. if (this.onSuccess) {
  77607. this.onSuccess(this);
  77608. }
  77609. onSuccess();
  77610. }
  77611. catch (e) {
  77612. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77613. }
  77614. };
  77615. return AbstractAssetTask;
  77616. }());
  77617. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77618. var AssetsProgressEvent = /** @class */ (function () {
  77619. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77620. this.remainingCount = remainingCount;
  77621. this.totalCount = totalCount;
  77622. this.task = task;
  77623. }
  77624. return AssetsProgressEvent;
  77625. }());
  77626. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77627. var MeshAssetTask = /** @class */ (function (_super) {
  77628. __extends(MeshAssetTask, _super);
  77629. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  77630. var _this = _super.call(this, name) || this;
  77631. _this.name = name;
  77632. _this.meshesNames = meshesNames;
  77633. _this.rootUrl = rootUrl;
  77634. _this.sceneFilename = sceneFilename;
  77635. return _this;
  77636. }
  77637. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77638. var _this = this;
  77639. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77640. _this.loadedMeshes = meshes;
  77641. _this.loadedParticleSystems = particleSystems;
  77642. _this.loadedSkeletons = skeletons;
  77643. onSuccess();
  77644. }, null, function (scene, message, exception) {
  77645. onError(message, exception);
  77646. });
  77647. };
  77648. return MeshAssetTask;
  77649. }(AbstractAssetTask));
  77650. BABYLON.MeshAssetTask = MeshAssetTask;
  77651. var TextFileAssetTask = /** @class */ (function (_super) {
  77652. __extends(TextFileAssetTask, _super);
  77653. function TextFileAssetTask(name, url) {
  77654. var _this = _super.call(this, name) || this;
  77655. _this.name = name;
  77656. _this.url = url;
  77657. return _this;
  77658. }
  77659. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77660. var _this = this;
  77661. scene._loadFile(this.url, function (data) {
  77662. _this.text = data;
  77663. onSuccess();
  77664. }, undefined, false, true, function (request, exception) {
  77665. if (request) {
  77666. onError(request.status + " " + request.statusText, exception);
  77667. }
  77668. });
  77669. };
  77670. return TextFileAssetTask;
  77671. }(AbstractAssetTask));
  77672. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77673. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77674. __extends(BinaryFileAssetTask, _super);
  77675. function BinaryFileAssetTask(name, url) {
  77676. var _this = _super.call(this, name) || this;
  77677. _this.name = name;
  77678. _this.url = url;
  77679. return _this;
  77680. }
  77681. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77682. var _this = this;
  77683. scene._loadFile(this.url, function (data) {
  77684. _this.data = data;
  77685. onSuccess();
  77686. }, undefined, true, true, function (request, exception) {
  77687. if (request) {
  77688. onError(request.status + " " + request.statusText, exception);
  77689. }
  77690. });
  77691. };
  77692. return BinaryFileAssetTask;
  77693. }(AbstractAssetTask));
  77694. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77695. var ImageAssetTask = /** @class */ (function (_super) {
  77696. __extends(ImageAssetTask, _super);
  77697. function ImageAssetTask(name, url) {
  77698. var _this = _super.call(this, name) || this;
  77699. _this.name = name;
  77700. _this.url = url;
  77701. return _this;
  77702. }
  77703. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77704. var _this = this;
  77705. var img = new Image();
  77706. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77707. img.onload = function () {
  77708. _this.image = img;
  77709. onSuccess();
  77710. };
  77711. img.onerror = function (err) {
  77712. onError("Error loading image", err);
  77713. };
  77714. img.src = this.url;
  77715. };
  77716. return ImageAssetTask;
  77717. }(AbstractAssetTask));
  77718. BABYLON.ImageAssetTask = ImageAssetTask;
  77719. var TextureAssetTask = /** @class */ (function (_super) {
  77720. __extends(TextureAssetTask, _super);
  77721. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  77722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77723. var _this = _super.call(this, name) || this;
  77724. _this.name = name;
  77725. _this.url = url;
  77726. _this.noMipmap = noMipmap;
  77727. _this.invertY = invertY;
  77728. _this.samplingMode = samplingMode;
  77729. return _this;
  77730. }
  77731. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77732. var onload = function () {
  77733. onSuccess();
  77734. };
  77735. var onerror = function (message, exception) {
  77736. onError(message, exception);
  77737. };
  77738. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77739. };
  77740. return TextureAssetTask;
  77741. }(AbstractAssetTask));
  77742. BABYLON.TextureAssetTask = TextureAssetTask;
  77743. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77744. __extends(CubeTextureAssetTask, _super);
  77745. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  77746. var _this = _super.call(this, name) || this;
  77747. _this.name = name;
  77748. _this.url = url;
  77749. _this.extensions = extensions;
  77750. _this.noMipmap = noMipmap;
  77751. _this.files = files;
  77752. return _this;
  77753. }
  77754. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77755. var onload = function () {
  77756. onSuccess();
  77757. };
  77758. var onerror = function (message, exception) {
  77759. onError(message, exception);
  77760. };
  77761. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77762. };
  77763. return CubeTextureAssetTask;
  77764. }(AbstractAssetTask));
  77765. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77766. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77767. __extends(HDRCubeTextureAssetTask, _super);
  77768. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77769. if (noMipmap === void 0) { noMipmap = false; }
  77770. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77771. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77772. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77773. var _this = _super.call(this, name) || this;
  77774. _this.name = name;
  77775. _this.url = url;
  77776. _this.size = size;
  77777. _this.noMipmap = noMipmap;
  77778. _this.generateHarmonics = generateHarmonics;
  77779. _this.useInGammaSpace = useInGammaSpace;
  77780. _this.usePMREMGenerator = usePMREMGenerator;
  77781. return _this;
  77782. }
  77783. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77784. var onload = function () {
  77785. onSuccess();
  77786. };
  77787. var onerror = function (message, exception) {
  77788. onError(message, exception);
  77789. };
  77790. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  77791. };
  77792. return HDRCubeTextureAssetTask;
  77793. }(AbstractAssetTask));
  77794. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  77795. var AssetsManager = /** @class */ (function () {
  77796. function AssetsManager(scene) {
  77797. this._isLoading = false;
  77798. this.tasks = new Array();
  77799. this.waitingTasksCount = 0;
  77800. //Observables
  77801. this.onTaskSuccessObservable = new BABYLON.Observable();
  77802. this.onTaskErrorObservable = new BABYLON.Observable();
  77803. this.onTasksDoneObservable = new BABYLON.Observable();
  77804. this.onProgressObservable = new BABYLON.Observable();
  77805. this.useDefaultLoadingScreen = true;
  77806. this._scene = scene;
  77807. }
  77808. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77809. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77810. this.tasks.push(task);
  77811. return task;
  77812. };
  77813. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77814. var task = new TextFileAssetTask(taskName, url);
  77815. this.tasks.push(task);
  77816. return task;
  77817. };
  77818. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77819. var task = new BinaryFileAssetTask(taskName, url);
  77820. this.tasks.push(task);
  77821. return task;
  77822. };
  77823. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77824. var task = new ImageAssetTask(taskName, url);
  77825. this.tasks.push(task);
  77826. return task;
  77827. };
  77828. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  77829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77830. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  77831. this.tasks.push(task);
  77832. return task;
  77833. };
  77834. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  77835. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  77836. this.tasks.push(task);
  77837. return task;
  77838. };
  77839. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77840. if (noMipmap === void 0) { noMipmap = false; }
  77841. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77842. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77843. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77844. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  77845. this.tasks.push(task);
  77846. return task;
  77847. };
  77848. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  77849. this.waitingTasksCount--;
  77850. try {
  77851. if (this.onProgress) {
  77852. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  77853. }
  77854. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  77855. }
  77856. catch (e) {
  77857. BABYLON.Tools.Error("Error running progress callbacks.");
  77858. console.log(e);
  77859. }
  77860. if (this.waitingTasksCount === 0) {
  77861. try {
  77862. if (this.onFinish) {
  77863. this.onFinish(this.tasks);
  77864. }
  77865. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77866. }
  77867. catch (e) {
  77868. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  77869. console.log(e);
  77870. }
  77871. this._isLoading = false;
  77872. this._scene.getEngine().hideLoadingUI();
  77873. }
  77874. };
  77875. AssetsManager.prototype._runTask = function (task) {
  77876. var _this = this;
  77877. var done = function () {
  77878. try {
  77879. if (_this.onTaskSuccess) {
  77880. _this.onTaskSuccess(task);
  77881. }
  77882. _this.onTaskSuccessObservable.notifyObservers(task);
  77883. _this._decreaseWaitingTasksCount(task);
  77884. }
  77885. catch (e) {
  77886. error("Error executing task success callbacks", e);
  77887. }
  77888. };
  77889. var error = function (message, exception) {
  77890. task.errorObject = task.errorObject || {
  77891. message: message,
  77892. exception: exception
  77893. };
  77894. if (_this.onTaskError) {
  77895. _this.onTaskError(task);
  77896. }
  77897. _this.onTaskErrorObservable.notifyObservers(task);
  77898. _this._decreaseWaitingTasksCount(task);
  77899. };
  77900. task.run(this._scene, done, error);
  77901. };
  77902. AssetsManager.prototype.reset = function () {
  77903. this._isLoading = false;
  77904. this.tasks = new Array();
  77905. return this;
  77906. };
  77907. AssetsManager.prototype.load = function () {
  77908. if (this._isLoading) {
  77909. return this;
  77910. }
  77911. this._isLoading = true;
  77912. this.waitingTasksCount = this.tasks.length;
  77913. if (this.waitingTasksCount === 0) {
  77914. if (this.onFinish) {
  77915. this.onFinish(this.tasks);
  77916. }
  77917. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77918. this._isLoading = false;
  77919. return this;
  77920. }
  77921. if (this.useDefaultLoadingScreen) {
  77922. this._scene.getEngine().displayLoadingUI();
  77923. }
  77924. for (var index = 0; index < this.tasks.length; index++) {
  77925. var task = this.tasks[index];
  77926. this._runTask(task);
  77927. }
  77928. return this;
  77929. };
  77930. return AssetsManager;
  77931. }());
  77932. BABYLON.AssetsManager = AssetsManager;
  77933. })(BABYLON || (BABYLON = {}));
  77934. //# sourceMappingURL=babylon.assetsManager.js.map
  77935. var BABYLON;
  77936. (function (BABYLON) {
  77937. var serializedGeometries = [];
  77938. var serializeGeometry = function (geometry, serializationGeometries) {
  77939. if (serializedGeometries[geometry.id]) {
  77940. return;
  77941. }
  77942. if (geometry.doNotSerialize) {
  77943. return;
  77944. }
  77945. if (geometry instanceof BABYLON.BoxGeometry) {
  77946. serializationGeometries.boxes.push(geometry.serialize());
  77947. }
  77948. else if (geometry instanceof BABYLON.SphereGeometry) {
  77949. serializationGeometries.spheres.push(geometry.serialize());
  77950. }
  77951. else if (geometry instanceof BABYLON.CylinderGeometry) {
  77952. serializationGeometries.cylinders.push(geometry.serialize());
  77953. }
  77954. else if (geometry instanceof BABYLON.TorusGeometry) {
  77955. serializationGeometries.toruses.push(geometry.serialize());
  77956. }
  77957. else if (geometry instanceof BABYLON.GroundGeometry) {
  77958. serializationGeometries.grounds.push(geometry.serialize());
  77959. }
  77960. else if (geometry instanceof BABYLON.Plane) {
  77961. serializationGeometries.planes.push(geometry.serialize());
  77962. }
  77963. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  77964. serializationGeometries.torusKnots.push(geometry.serialize());
  77965. }
  77966. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  77967. throw new Error("Unknown primitive type");
  77968. }
  77969. else {
  77970. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  77971. }
  77972. serializedGeometries[geometry.id] = true;
  77973. };
  77974. var serializeMesh = function (mesh, serializationScene) {
  77975. var serializationObject = {};
  77976. // Geometry
  77977. var geometry = mesh._geometry;
  77978. if (geometry) {
  77979. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  77980. // 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
  77981. serializeGeometry(geometry, serializationScene.geometries);
  77982. }
  77983. }
  77984. // Custom
  77985. if (mesh.serialize) {
  77986. mesh.serialize(serializationObject);
  77987. }
  77988. return serializationObject;
  77989. };
  77990. var finalizeSingleMesh = function (mesh, serializationObject) {
  77991. //only works if the mesh is already loaded
  77992. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77993. //serialize material
  77994. if (mesh.material) {
  77995. if (mesh.material instanceof BABYLON.StandardMaterial) {
  77996. serializationObject.materials = serializationObject.materials || [];
  77997. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77998. serializationObject.materials.push(mesh.material.serialize());
  77999. }
  78000. }
  78001. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  78002. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  78003. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78004. serializationObject.multiMaterials.push(mesh.material.serialize());
  78005. }
  78006. }
  78007. }
  78008. //serialize geometry
  78009. var geometry = mesh._geometry;
  78010. if (geometry) {
  78011. if (!serializationObject.geometries) {
  78012. serializationObject.geometries = {};
  78013. serializationObject.geometries.boxes = [];
  78014. serializationObject.geometries.spheres = [];
  78015. serializationObject.geometries.cylinders = [];
  78016. serializationObject.geometries.toruses = [];
  78017. serializationObject.geometries.grounds = [];
  78018. serializationObject.geometries.planes = [];
  78019. serializationObject.geometries.torusKnots = [];
  78020. serializationObject.geometries.vertexData = [];
  78021. }
  78022. serializeGeometry(geometry, serializationObject.geometries);
  78023. }
  78024. // Skeletons
  78025. if (mesh.skeleton) {
  78026. serializationObject.skeletons = serializationObject.skeletons || [];
  78027. serializationObject.skeletons.push(mesh.skeleton.serialize());
  78028. }
  78029. //serialize the actual mesh
  78030. serializationObject.meshes = serializationObject.meshes || [];
  78031. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78032. }
  78033. };
  78034. var SceneSerializer = /** @class */ (function () {
  78035. function SceneSerializer() {
  78036. }
  78037. SceneSerializer.ClearCache = function () {
  78038. serializedGeometries = [];
  78039. };
  78040. SceneSerializer.Serialize = function (scene) {
  78041. var serializationObject = {};
  78042. SceneSerializer.ClearCache();
  78043. // Scene
  78044. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  78045. serializationObject.autoClear = scene.autoClear;
  78046. serializationObject.clearColor = scene.clearColor.asArray();
  78047. serializationObject.ambientColor = scene.ambientColor.asArray();
  78048. serializationObject.gravity = scene.gravity.asArray();
  78049. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  78050. serializationObject.workerCollisions = scene.workerCollisions;
  78051. // Fog
  78052. if (scene.fogMode && scene.fogMode !== 0) {
  78053. serializationObject.fogMode = scene.fogMode;
  78054. serializationObject.fogColor = scene.fogColor.asArray();
  78055. serializationObject.fogStart = scene.fogStart;
  78056. serializationObject.fogEnd = scene.fogEnd;
  78057. serializationObject.fogDensity = scene.fogDensity;
  78058. }
  78059. //Physics
  78060. if (scene.isPhysicsEnabled()) {
  78061. var physicEngine = scene.getPhysicsEngine();
  78062. if (physicEngine) {
  78063. serializationObject.physicsEnabled = true;
  78064. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  78065. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  78066. }
  78067. }
  78068. // Metadata
  78069. if (scene.metadata) {
  78070. serializationObject.metadata = scene.metadata;
  78071. }
  78072. // Morph targets
  78073. serializationObject.morphTargetManagers = [];
  78074. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  78075. var abstractMesh = _a[_i];
  78076. var manager = abstractMesh.morphTargetManager;
  78077. if (manager) {
  78078. serializationObject.morphTargetManagers.push(manager.serialize());
  78079. }
  78080. }
  78081. // Lights
  78082. serializationObject.lights = [];
  78083. var index;
  78084. var light;
  78085. for (index = 0; index < scene.lights.length; index++) {
  78086. light = scene.lights[index];
  78087. if (!light.doNotSerialize) {
  78088. serializationObject.lights.push(light.serialize());
  78089. }
  78090. }
  78091. // Cameras
  78092. serializationObject.cameras = [];
  78093. for (index = 0; index < scene.cameras.length; index++) {
  78094. var camera = scene.cameras[index];
  78095. if (!camera.doNotSerialize) {
  78096. serializationObject.cameras.push(camera.serialize());
  78097. }
  78098. }
  78099. if (scene.activeCamera) {
  78100. serializationObject.activeCameraID = scene.activeCamera.id;
  78101. }
  78102. // Animations
  78103. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  78104. // Materials
  78105. serializationObject.materials = [];
  78106. serializationObject.multiMaterials = [];
  78107. var material;
  78108. for (index = 0; index < scene.materials.length; index++) {
  78109. material = scene.materials[index];
  78110. if (!material.doNotSerialize) {
  78111. serializationObject.materials.push(material.serialize());
  78112. }
  78113. }
  78114. // MultiMaterials
  78115. serializationObject.multiMaterials = [];
  78116. for (index = 0; index < scene.multiMaterials.length; index++) {
  78117. var multiMaterial = scene.multiMaterials[index];
  78118. serializationObject.multiMaterials.push(multiMaterial.serialize());
  78119. }
  78120. // Environment texture
  78121. if (scene.environmentTexture) {
  78122. serializationObject.environmentTexture = scene.environmentTexture.name;
  78123. }
  78124. // Skeletons
  78125. serializationObject.skeletons = [];
  78126. for (index = 0; index < scene.skeletons.length; index++) {
  78127. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  78128. }
  78129. // Transform nodes
  78130. serializationObject.transformNodes = [];
  78131. for (index = 0; index < scene.transformNodes.length; index++) {
  78132. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  78133. }
  78134. // Geometries
  78135. serializationObject.geometries = {};
  78136. serializationObject.geometries.boxes = [];
  78137. serializationObject.geometries.spheres = [];
  78138. serializationObject.geometries.cylinders = [];
  78139. serializationObject.geometries.toruses = [];
  78140. serializationObject.geometries.grounds = [];
  78141. serializationObject.geometries.planes = [];
  78142. serializationObject.geometries.torusKnots = [];
  78143. serializationObject.geometries.vertexData = [];
  78144. serializedGeometries = [];
  78145. var geometries = scene.getGeometries();
  78146. for (index = 0; index < geometries.length; index++) {
  78147. var geometry = geometries[index];
  78148. if (geometry.isReady()) {
  78149. serializeGeometry(geometry, serializationObject.geometries);
  78150. }
  78151. }
  78152. // Meshes
  78153. serializationObject.meshes = [];
  78154. for (index = 0; index < scene.meshes.length; index++) {
  78155. var abstractMesh = scene.meshes[index];
  78156. if (abstractMesh instanceof BABYLON.Mesh) {
  78157. var mesh = abstractMesh;
  78158. if (!mesh.doNotSerialize) {
  78159. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78160. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78161. }
  78162. }
  78163. }
  78164. }
  78165. // Particles Systems
  78166. serializationObject.particleSystems = [];
  78167. for (index = 0; index < scene.particleSystems.length; index++) {
  78168. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  78169. }
  78170. // Lens flares
  78171. serializationObject.lensFlareSystems = [];
  78172. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  78173. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  78174. }
  78175. // Shadows
  78176. serializationObject.shadowGenerators = [];
  78177. for (index = 0; index < scene.lights.length; index++) {
  78178. light = scene.lights[index];
  78179. var shadowGenerator = light.getShadowGenerator();
  78180. if (shadowGenerator) {
  78181. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78182. }
  78183. }
  78184. // Action Manager
  78185. if (scene.actionManager) {
  78186. serializationObject.actions = scene.actionManager.serialize("scene");
  78187. }
  78188. // Audio
  78189. serializationObject.sounds = [];
  78190. for (index = 0; index < scene.soundTracks.length; index++) {
  78191. var soundtrack = scene.soundTracks[index];
  78192. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  78193. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  78194. }
  78195. }
  78196. return serializationObject;
  78197. };
  78198. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  78199. if (withParents === void 0) { withParents = false; }
  78200. if (withChildren === void 0) { withChildren = false; }
  78201. var serializationObject = {};
  78202. SceneSerializer.ClearCache();
  78203. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  78204. if (withParents || withChildren) {
  78205. //deliberate for loop! not for each, appended should be processed as well.
  78206. for (var i = 0; i < toSerialize.length; ++i) {
  78207. if (withChildren) {
  78208. toSerialize[i].getDescendants().forEach(function (node) {
  78209. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  78210. toSerialize.push(node);
  78211. }
  78212. });
  78213. }
  78214. //make sure the array doesn't contain the object already
  78215. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  78216. toSerialize.push(toSerialize[i].parent);
  78217. }
  78218. }
  78219. }
  78220. toSerialize.forEach(function (mesh) {
  78221. finalizeSingleMesh(mesh, serializationObject);
  78222. });
  78223. return serializationObject;
  78224. };
  78225. return SceneSerializer;
  78226. }());
  78227. BABYLON.SceneSerializer = SceneSerializer;
  78228. })(BABYLON || (BABYLON = {}));
  78229. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78230. var BABYLON;
  78231. (function (BABYLON) {
  78232. var ReflectionProbe = /** @class */ (function () {
  78233. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78234. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78235. var _this = this;
  78236. this.name = name;
  78237. this._viewMatrix = BABYLON.Matrix.Identity();
  78238. this._target = BABYLON.Vector3.Zero();
  78239. this._add = BABYLON.Vector3.Zero();
  78240. this.invertYAxis = false;
  78241. this.position = BABYLON.Vector3.Zero();
  78242. this._scene = scene;
  78243. this._scene.reflectionProbes.push(this);
  78244. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78245. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78246. switch (faceIndex) {
  78247. case 0:
  78248. _this._add.copyFromFloats(1, 0, 0);
  78249. break;
  78250. case 1:
  78251. _this._add.copyFromFloats(-1, 0, 0);
  78252. break;
  78253. case 2:
  78254. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78255. break;
  78256. case 3:
  78257. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78258. break;
  78259. case 4:
  78260. _this._add.copyFromFloats(0, 0, 1);
  78261. break;
  78262. case 5:
  78263. _this._add.copyFromFloats(0, 0, -1);
  78264. break;
  78265. }
  78266. if (_this._attachedMesh) {
  78267. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78268. }
  78269. _this.position.addToRef(_this._add, _this._target);
  78270. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78271. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78272. scene._forcedViewPosition = _this.position;
  78273. });
  78274. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78275. scene._forcedViewPosition = null;
  78276. scene.updateTransformMatrix(true);
  78277. });
  78278. if (scene.activeCamera) {
  78279. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78280. }
  78281. }
  78282. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78283. get: function () {
  78284. return this._renderTargetTexture.samples;
  78285. },
  78286. set: function (value) {
  78287. this._renderTargetTexture.samples = value;
  78288. },
  78289. enumerable: true,
  78290. configurable: true
  78291. });
  78292. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78293. get: function () {
  78294. return this._renderTargetTexture.refreshRate;
  78295. },
  78296. set: function (value) {
  78297. this._renderTargetTexture.refreshRate = value;
  78298. },
  78299. enumerable: true,
  78300. configurable: true
  78301. });
  78302. ReflectionProbe.prototype.getScene = function () {
  78303. return this._scene;
  78304. };
  78305. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78306. get: function () {
  78307. return this._renderTargetTexture;
  78308. },
  78309. enumerable: true,
  78310. configurable: true
  78311. });
  78312. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78313. get: function () {
  78314. return this._renderTargetTexture.renderList;
  78315. },
  78316. enumerable: true,
  78317. configurable: true
  78318. });
  78319. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78320. this._attachedMesh = mesh;
  78321. };
  78322. /**
  78323. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78324. *
  78325. * @param renderingGroupId The rendering group id corresponding to its index
  78326. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78327. */
  78328. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78329. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78330. };
  78331. ReflectionProbe.prototype.dispose = function () {
  78332. var index = this._scene.reflectionProbes.indexOf(this);
  78333. if (index !== -1) {
  78334. // Remove from the scene if found
  78335. this._scene.reflectionProbes.splice(index, 1);
  78336. }
  78337. if (this._renderTargetTexture) {
  78338. this._renderTargetTexture.dispose();
  78339. this._renderTargetTexture = null;
  78340. }
  78341. };
  78342. return ReflectionProbe;
  78343. }());
  78344. BABYLON.ReflectionProbe = ReflectionProbe;
  78345. })(BABYLON || (BABYLON = {}));
  78346. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78347. var BABYLON;
  78348. (function (BABYLON) {
  78349. var Layer = /** @class */ (function () {
  78350. function Layer(name, imgUrl, scene, isBackground, color) {
  78351. this.name = name;
  78352. this.scale = new BABYLON.Vector2(1, 1);
  78353. this.offset = new BABYLON.Vector2(0, 0);
  78354. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78355. this.layerMask = 0x0FFFFFFF;
  78356. this._vertexBuffers = {};
  78357. // Events
  78358. /**
  78359. * An event triggered when the layer is disposed.
  78360. * @type {BABYLON.Observable}
  78361. */
  78362. this.onDisposeObservable = new BABYLON.Observable();
  78363. /**
  78364. * An event triggered before rendering the scene
  78365. * @type {BABYLON.Observable}
  78366. */
  78367. this.onBeforeRenderObservable = new BABYLON.Observable();
  78368. /**
  78369. * An event triggered after rendering the scene
  78370. * @type {BABYLON.Observable}
  78371. */
  78372. this.onAfterRenderObservable = new BABYLON.Observable();
  78373. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78374. this.isBackground = isBackground === undefined ? true : isBackground;
  78375. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78376. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78377. this._scene.layers.push(this);
  78378. var engine = this._scene.getEngine();
  78379. // VBO
  78380. var vertices = [];
  78381. vertices.push(1, 1);
  78382. vertices.push(-1, 1);
  78383. vertices.push(-1, -1);
  78384. vertices.push(1, -1);
  78385. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78386. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78387. this._createIndexBuffer();
  78388. // Effects
  78389. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78390. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78391. }
  78392. Object.defineProperty(Layer.prototype, "onDispose", {
  78393. set: function (callback) {
  78394. if (this._onDisposeObserver) {
  78395. this.onDisposeObservable.remove(this._onDisposeObserver);
  78396. }
  78397. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78398. },
  78399. enumerable: true,
  78400. configurable: true
  78401. });
  78402. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78403. set: function (callback) {
  78404. if (this._onBeforeRenderObserver) {
  78405. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78406. }
  78407. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78408. },
  78409. enumerable: true,
  78410. configurable: true
  78411. });
  78412. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78413. set: function (callback) {
  78414. if (this._onAfterRenderObserver) {
  78415. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78416. }
  78417. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78418. },
  78419. enumerable: true,
  78420. configurable: true
  78421. });
  78422. Layer.prototype._createIndexBuffer = function () {
  78423. var engine = this._scene.getEngine();
  78424. // Indices
  78425. var indices = [];
  78426. indices.push(0);
  78427. indices.push(1);
  78428. indices.push(2);
  78429. indices.push(0);
  78430. indices.push(2);
  78431. indices.push(3);
  78432. this._indexBuffer = engine.createIndexBuffer(indices);
  78433. };
  78434. Layer.prototype._rebuild = function () {
  78435. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78436. if (vb) {
  78437. vb._rebuild();
  78438. }
  78439. this._createIndexBuffer();
  78440. };
  78441. Layer.prototype.render = function () {
  78442. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78443. // Check
  78444. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78445. return;
  78446. var engine = this._scene.getEngine();
  78447. this.onBeforeRenderObservable.notifyObservers(this);
  78448. // Render
  78449. engine.enableEffect(currentEffect);
  78450. engine.setState(false);
  78451. // Texture
  78452. currentEffect.setTexture("textureSampler", this.texture);
  78453. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78454. // Color
  78455. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78456. // Scale / offset
  78457. currentEffect.setVector2("offset", this.offset);
  78458. currentEffect.setVector2("scale", this.scale);
  78459. // VBOs
  78460. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78461. // Draw order
  78462. if (!this.alphaTest) {
  78463. engine.setAlphaMode(this.alphaBlendingMode);
  78464. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78465. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78466. }
  78467. else {
  78468. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78469. }
  78470. this.onAfterRenderObservable.notifyObservers(this);
  78471. };
  78472. Layer.prototype.dispose = function () {
  78473. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78474. if (vertexBuffer) {
  78475. vertexBuffer.dispose();
  78476. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78477. }
  78478. if (this._indexBuffer) {
  78479. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78480. this._indexBuffer = null;
  78481. }
  78482. if (this.texture) {
  78483. this.texture.dispose();
  78484. this.texture = null;
  78485. }
  78486. // Remove from scene
  78487. var index = this._scene.layers.indexOf(this);
  78488. this._scene.layers.splice(index, 1);
  78489. // Callback
  78490. this.onDisposeObservable.notifyObservers(this);
  78491. this.onDisposeObservable.clear();
  78492. this.onAfterRenderObservable.clear();
  78493. this.onBeforeRenderObservable.clear();
  78494. };
  78495. return Layer;
  78496. }());
  78497. BABYLON.Layer = Layer;
  78498. })(BABYLON || (BABYLON = {}));
  78499. //# sourceMappingURL=babylon.layer.js.map
  78500. var BABYLON;
  78501. (function (BABYLON) {
  78502. var TextureTools = /** @class */ (function () {
  78503. function TextureTools() {
  78504. }
  78505. /**
  78506. * Uses the GPU to create a copy texture rescaled at a given size
  78507. * @param texture Texture to copy from
  78508. * @param width Desired width
  78509. * @param height Desired height
  78510. * @return Generated texture
  78511. */
  78512. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78513. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78514. var scene = texture.getScene();
  78515. var engine = scene.getEngine();
  78516. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78517. rtt.wrapU = texture.wrapU;
  78518. rtt.wrapV = texture.wrapV;
  78519. rtt.uOffset = texture.uOffset;
  78520. rtt.vOffset = texture.vOffset;
  78521. rtt.uScale = texture.uScale;
  78522. rtt.vScale = texture.vScale;
  78523. rtt.uAng = texture.uAng;
  78524. rtt.vAng = texture.vAng;
  78525. rtt.wAng = texture.wAng;
  78526. rtt.coordinatesIndex = texture.coordinatesIndex;
  78527. rtt.level = texture.level;
  78528. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78529. rtt._texture.isReady = false;
  78530. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78531. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78532. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78533. passPostProcess.getEffect().executeWhenCompiled(function () {
  78534. passPostProcess.onApply = function (effect) {
  78535. effect.setTexture("textureSampler", texture);
  78536. };
  78537. var internalTexture = rtt.getInternalTexture();
  78538. if (internalTexture) {
  78539. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78540. engine.unBindFramebuffer(internalTexture);
  78541. rtt.disposeFramebufferObjects();
  78542. passPostProcess.dispose();
  78543. internalTexture.isReady = true;
  78544. }
  78545. });
  78546. return rtt;
  78547. };
  78548. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78549. if (!scene._environmentBRDFTexture) {
  78550. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78551. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78552. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78553. scene._environmentBRDFTexture = texture;
  78554. }
  78555. return scene._environmentBRDFTexture;
  78556. };
  78557. 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=";
  78558. return TextureTools;
  78559. }());
  78560. BABYLON.TextureTools = TextureTools;
  78561. })(BABYLON || (BABYLON = {}));
  78562. //# sourceMappingURL=babylon.textureTools.js.map
  78563. var BABYLON;
  78564. (function (BABYLON) {
  78565. var FramingBehavior = /** @class */ (function () {
  78566. function FramingBehavior() {
  78567. this._mode = FramingBehavior.FitFrustumSidesMode;
  78568. this._radiusScale = 1.0;
  78569. this._positionScale = 0.5;
  78570. this._defaultElevation = 0.3;
  78571. this._elevationReturnTime = 1500;
  78572. this._elevationReturnWaitTime = 1000;
  78573. this._zoomStopsAnimation = false;
  78574. this._framingTime = 1500;
  78575. this._isPointerDown = false;
  78576. this._lastInteractionTime = -Infinity;
  78577. // Framing control
  78578. this._animatables = new Array();
  78579. this._betaIsAnimating = false;
  78580. }
  78581. Object.defineProperty(FramingBehavior.prototype, "name", {
  78582. get: function () {
  78583. return "Framing";
  78584. },
  78585. enumerable: true,
  78586. configurable: true
  78587. });
  78588. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78589. /**
  78590. * Gets current mode used by the behavior.
  78591. */
  78592. get: function () {
  78593. return this._mode;
  78594. },
  78595. /**
  78596. * Sets the current mode used by the behavior
  78597. */
  78598. set: function (mode) {
  78599. this._mode = mode;
  78600. },
  78601. enumerable: true,
  78602. configurable: true
  78603. });
  78604. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78605. /**
  78606. * Gets the scale applied to the radius
  78607. */
  78608. get: function () {
  78609. return this._radiusScale;
  78610. },
  78611. /**
  78612. * Sets the scale applied to the radius (1 by default)
  78613. */
  78614. set: function (radius) {
  78615. this._radiusScale = radius;
  78616. },
  78617. enumerable: true,
  78618. configurable: true
  78619. });
  78620. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78621. /**
  78622. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78623. */
  78624. get: function () {
  78625. return this._positionScale;
  78626. },
  78627. /**
  78628. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78629. */
  78630. set: function (scale) {
  78631. this._positionScale = scale;
  78632. },
  78633. enumerable: true,
  78634. configurable: true
  78635. });
  78636. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78637. /**
  78638. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78639. * behaviour is triggered, in radians.
  78640. */
  78641. get: function () {
  78642. return this._defaultElevation;
  78643. },
  78644. /**
  78645. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78646. * behaviour is triggered, in radians.
  78647. */
  78648. set: function (elevation) {
  78649. this._defaultElevation = elevation;
  78650. },
  78651. enumerable: true,
  78652. configurable: true
  78653. });
  78654. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78655. /**
  78656. * Gets the time (in milliseconds) taken to return to the default beta position.
  78657. * Negative value indicates camera should not return to default.
  78658. */
  78659. get: function () {
  78660. return this._elevationReturnTime;
  78661. },
  78662. /**
  78663. * Sets the time (in milliseconds) taken to return to the default beta position.
  78664. * Negative value indicates camera should not return to default.
  78665. */
  78666. set: function (speed) {
  78667. this._elevationReturnTime = speed;
  78668. },
  78669. enumerable: true,
  78670. configurable: true
  78671. });
  78672. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78673. /**
  78674. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78675. */
  78676. get: function () {
  78677. return this._elevationReturnWaitTime;
  78678. },
  78679. /**
  78680. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78681. */
  78682. set: function (time) {
  78683. this._elevationReturnWaitTime = time;
  78684. },
  78685. enumerable: true,
  78686. configurable: true
  78687. });
  78688. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  78689. /**
  78690. * Gets the flag that indicates if user zooming should stop animation.
  78691. */
  78692. get: function () {
  78693. return this._zoomStopsAnimation;
  78694. },
  78695. /**
  78696. * Sets the flag that indicates if user zooming should stop animation.
  78697. */
  78698. set: function (flag) {
  78699. this._zoomStopsAnimation = flag;
  78700. },
  78701. enumerable: true,
  78702. configurable: true
  78703. });
  78704. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  78705. /**
  78706. * Gets the transition time when framing the mesh, in milliseconds
  78707. */
  78708. get: function () {
  78709. return this._framingTime;
  78710. },
  78711. /**
  78712. * Sets the transition time when framing the mesh, in milliseconds
  78713. */
  78714. set: function (time) {
  78715. this._framingTime = time;
  78716. },
  78717. enumerable: true,
  78718. configurable: true
  78719. });
  78720. FramingBehavior.prototype.init = function () {
  78721. // Do notihng
  78722. };
  78723. FramingBehavior.prototype.attach = function (camera) {
  78724. var _this = this;
  78725. this._attachedCamera = camera;
  78726. var scene = this._attachedCamera.getScene();
  78727. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  78728. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78729. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78730. _this._isPointerDown = true;
  78731. return;
  78732. }
  78733. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78734. _this._isPointerDown = false;
  78735. }
  78736. });
  78737. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78738. if (mesh) {
  78739. _this.zoomOnMesh(mesh);
  78740. }
  78741. });
  78742. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78743. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78744. _this._applyUserInteraction();
  78745. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  78746. // back to the default position after a given timeout
  78747. _this._maintainCameraAboveGround();
  78748. });
  78749. };
  78750. FramingBehavior.prototype.detach = function () {
  78751. if (!this._attachedCamera) {
  78752. return;
  78753. }
  78754. var scene = this._attachedCamera.getScene();
  78755. if (this._onPrePointerObservableObserver) {
  78756. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78757. }
  78758. if (this._onAfterCheckInputsObserver) {
  78759. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78760. }
  78761. if (this._onMeshTargetChangedObserver) {
  78762. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78763. }
  78764. this._attachedCamera = null;
  78765. };
  78766. /**
  78767. * Targets the given mesh and updates zoom level accordingly.
  78768. * @param mesh The mesh to target.
  78769. * @param radius Optional. If a cached radius position already exists, overrides default.
  78770. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78771. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78772. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78773. */
  78774. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78775. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78776. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78777. mesh.computeWorldMatrix(true);
  78778. var boundingBox = mesh.getBoundingInfo().boundingBox;
  78779. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  78780. };
  78781. /**
  78782. * Targets the given mesh with its children and updates zoom level accordingly.
  78783. * @param mesh The mesh to target.
  78784. * @param radius Optional. If a cached radius position already exists, overrides default.
  78785. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78786. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78787. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78788. */
  78789. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78790. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78791. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78792. mesh.computeWorldMatrix(true);
  78793. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  78794. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  78795. };
  78796. /**
  78797. * Targets the given meshes with their children and updates zoom level accordingly.
  78798. * @param meshes The mesh to target.
  78799. * @param radius Optional. If a cached radius position already exists, overrides default.
  78800. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78801. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78802. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78803. */
  78804. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  78805. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78806. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78807. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  78808. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  78809. for (var i = 0; i < meshes.length; i++) {
  78810. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  78811. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  78812. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  78813. }
  78814. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  78815. };
  78816. /**
  78817. * Targets the given mesh and updates zoom level accordingly.
  78818. * @param mesh The mesh to target.
  78819. * @param radius Optional. If a cached radius position already exists, overrides default.
  78820. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78821. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78822. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78823. */
  78824. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  78825. var _this = this;
  78826. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78827. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78828. var zoomTarget;
  78829. if (!this._attachedCamera) {
  78830. return;
  78831. }
  78832. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  78833. var bottom = minimumWorld.y;
  78834. var top = maximumWorld.y;
  78835. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  78836. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  78837. if (focusOnOriginXZ) {
  78838. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  78839. }
  78840. else {
  78841. var centerWorld = minimumWorld.add(radiusWorld);
  78842. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  78843. }
  78844. if (!this._vectorTransition) {
  78845. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  78846. }
  78847. this._betaIsAnimating = true;
  78848. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  78849. if (animatable) {
  78850. this._animatables.push(animatable);
  78851. }
  78852. // sets the radius and lower radius bounds
  78853. // Small delta ensures camera is not always at lower zoom limit.
  78854. var radius = 0;
  78855. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  78856. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78857. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  78858. radius = position;
  78859. }
  78860. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78861. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78862. if (this._attachedCamera.lowerRadiusLimit === null) {
  78863. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  78864. }
  78865. }
  78866. // Set sensibilities
  78867. var extend = maximumWorld.subtract(minimumWorld).length();
  78868. this._attachedCamera.panningSensibility = 5000 / extend;
  78869. this._attachedCamera.wheelPrecision = 100 / radius;
  78870. // transition to new radius
  78871. if (!this._radiusTransition) {
  78872. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78873. }
  78874. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  78875. if (onAnimationEnd) {
  78876. onAnimationEnd();
  78877. }
  78878. if (_this._attachedCamera) {
  78879. _this._attachedCamera.storeState();
  78880. }
  78881. });
  78882. if (animatable) {
  78883. this._animatables.push(animatable);
  78884. }
  78885. };
  78886. /**
  78887. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  78888. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  78889. * frustum width.
  78890. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  78891. * to fully enclose the mesh in the viewing frustum.
  78892. */
  78893. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  78894. var size = maximumWorld.subtract(minimumWorld);
  78895. var boxVectorGlobalDiagonal = size.length();
  78896. var frustumSlope = this._getFrustumSlope();
  78897. // Formula for setting distance
  78898. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  78899. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  78900. // Horizon distance
  78901. var radius = radiusWithoutFraming * this._radiusScale;
  78902. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  78903. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  78904. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  78905. var camera = this._attachedCamera;
  78906. if (!camera) {
  78907. return 0;
  78908. }
  78909. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78910. // Don't exceed the requested limit
  78911. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  78912. }
  78913. // Don't exceed the upper radius limit
  78914. if (camera.upperRadiusLimit) {
  78915. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  78916. }
  78917. return distance;
  78918. };
  78919. /**
  78920. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  78921. * is automatically returned to its default position (expected to be above ground plane).
  78922. */
  78923. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  78924. var _this = this;
  78925. if (this._elevationReturnTime < 0) {
  78926. return;
  78927. }
  78928. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  78929. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  78930. var limitBeta = Math.PI * 0.5;
  78931. // Bring the camera back up if below the ground plane
  78932. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  78933. this._betaIsAnimating = true;
  78934. //Transition to new position
  78935. this.stopAllAnimations();
  78936. if (!this._betaTransition) {
  78937. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78938. }
  78939. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  78940. _this._clearAnimationLocks();
  78941. _this.stopAllAnimations();
  78942. });
  78943. if (animatabe) {
  78944. this._animatables.push(animatabe);
  78945. }
  78946. }
  78947. };
  78948. /**
  78949. * Returns the frustum slope based on the canvas ratio and camera FOV
  78950. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  78951. */
  78952. FramingBehavior.prototype._getFrustumSlope = function () {
  78953. // Calculate the viewport ratio
  78954. // Aspect Ratio is Height/Width.
  78955. var camera = this._attachedCamera;
  78956. if (!camera) {
  78957. return BABYLON.Vector2.Zero();
  78958. }
  78959. var engine = camera.getScene().getEngine();
  78960. var aspectRatio = engine.getAspectRatio(camera);
  78961. // Camera FOV is the vertical field of view (top-bottom) in radians.
  78962. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  78963. var frustumSlopeY = Math.tan(camera.fov / 2);
  78964. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  78965. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  78966. // along the forward vector.
  78967. var frustumSlopeX = frustumSlopeY * aspectRatio;
  78968. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  78969. };
  78970. /**
  78971. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  78972. */
  78973. FramingBehavior.prototype._clearAnimationLocks = function () {
  78974. this._betaIsAnimating = false;
  78975. };
  78976. /**
  78977. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  78978. */
  78979. FramingBehavior.prototype._applyUserInteraction = function () {
  78980. if (this.isUserIsMoving) {
  78981. this._lastInteractionTime = BABYLON.Tools.Now;
  78982. this.stopAllAnimations();
  78983. this._clearAnimationLocks();
  78984. }
  78985. };
  78986. /**
  78987. * Stops and removes all animations that have been applied to the camera
  78988. */
  78989. FramingBehavior.prototype.stopAllAnimations = function () {
  78990. if (this._attachedCamera) {
  78991. this._attachedCamera.animations = [];
  78992. }
  78993. while (this._animatables.length) {
  78994. if (this._animatables[0]) {
  78995. this._animatables[0].onAnimationEnd = null;
  78996. this._animatables[0].stop();
  78997. }
  78998. this._animatables.shift();
  78999. }
  79000. };
  79001. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  79002. /**
  79003. * Gets a value indicating if the user is moving the camera
  79004. */
  79005. get: function () {
  79006. if (!this._attachedCamera) {
  79007. return false;
  79008. }
  79009. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79010. this._attachedCamera.inertialBetaOffset !== 0 ||
  79011. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79012. this._attachedCamera.inertialPanningX !== 0 ||
  79013. this._attachedCamera.inertialPanningY !== 0 ||
  79014. this._isPointerDown;
  79015. },
  79016. enumerable: true,
  79017. configurable: true
  79018. });
  79019. /**
  79020. * The easing function used by animations
  79021. */
  79022. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  79023. /**
  79024. * The easing mode used by animations
  79025. */
  79026. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  79027. // Statics
  79028. /**
  79029. * The camera can move all the way towards the mesh.
  79030. */
  79031. FramingBehavior.IgnoreBoundsSizeMode = 0;
  79032. /**
  79033. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  79034. */
  79035. FramingBehavior.FitFrustumSidesMode = 1;
  79036. return FramingBehavior;
  79037. }());
  79038. BABYLON.FramingBehavior = FramingBehavior;
  79039. })(BABYLON || (BABYLON = {}));
  79040. //# sourceMappingURL=babylon.framingBehavior.js.map
  79041. var BABYLON;
  79042. (function (BABYLON) {
  79043. /**
  79044. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  79045. */
  79046. var BouncingBehavior = /** @class */ (function () {
  79047. function BouncingBehavior() {
  79048. /**
  79049. * The duration of the animation, in milliseconds
  79050. */
  79051. this.transitionDuration = 450;
  79052. /**
  79053. * Length of the distance animated by the transition when lower radius is reached
  79054. */
  79055. this.lowerRadiusTransitionRange = 2;
  79056. /**
  79057. * Length of the distance animated by the transition when upper radius is reached
  79058. */
  79059. this.upperRadiusTransitionRange = -2;
  79060. this._autoTransitionRange = false;
  79061. // Animations
  79062. this._radiusIsAnimating = false;
  79063. this._radiusBounceTransition = null;
  79064. this._animatables = new Array();
  79065. }
  79066. Object.defineProperty(BouncingBehavior.prototype, "name", {
  79067. get: function () {
  79068. return "Bouncing";
  79069. },
  79070. enumerable: true,
  79071. configurable: true
  79072. });
  79073. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  79074. /**
  79075. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79076. */
  79077. get: function () {
  79078. return this._autoTransitionRange;
  79079. },
  79080. /**
  79081. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79082. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  79083. */
  79084. set: function (value) {
  79085. var _this = this;
  79086. if (this._autoTransitionRange === value) {
  79087. return;
  79088. }
  79089. this._autoTransitionRange = value;
  79090. var camera = this._attachedCamera;
  79091. if (!camera) {
  79092. return;
  79093. }
  79094. if (value) {
  79095. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79096. if (!mesh) {
  79097. return;
  79098. }
  79099. mesh.computeWorldMatrix(true);
  79100. var diagonal = mesh.getBoundingInfo().diagonalLength;
  79101. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  79102. _this.upperRadiusTransitionRange = diagonal * 0.05;
  79103. });
  79104. }
  79105. else if (this._onMeshTargetChangedObserver) {
  79106. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79107. }
  79108. },
  79109. enumerable: true,
  79110. configurable: true
  79111. });
  79112. BouncingBehavior.prototype.init = function () {
  79113. // Do notihng
  79114. };
  79115. BouncingBehavior.prototype.attach = function (camera) {
  79116. var _this = this;
  79117. this._attachedCamera = camera;
  79118. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79119. if (!_this._attachedCamera) {
  79120. return;
  79121. }
  79122. // Add the bounce animation to the lower radius limit
  79123. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  79124. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  79125. }
  79126. // Add the bounce animation to the upper radius limit
  79127. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  79128. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  79129. }
  79130. });
  79131. };
  79132. BouncingBehavior.prototype.detach = function () {
  79133. if (!this._attachedCamera) {
  79134. return;
  79135. }
  79136. if (this._onAfterCheckInputsObserver) {
  79137. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79138. }
  79139. if (this._onMeshTargetChangedObserver) {
  79140. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79141. }
  79142. this._attachedCamera = null;
  79143. };
  79144. /**
  79145. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  79146. * @param radiusLimit The limit to check against.
  79147. * @return Bool to indicate if at limit.
  79148. */
  79149. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  79150. if (!this._attachedCamera) {
  79151. return false;
  79152. }
  79153. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  79154. return true;
  79155. }
  79156. return false;
  79157. };
  79158. /**
  79159. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  79160. * @param radiusDelta The delta by which to animate to. Can be negative.
  79161. */
  79162. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  79163. var _this = this;
  79164. if (!this._attachedCamera) {
  79165. return;
  79166. }
  79167. if (!this._radiusBounceTransition) {
  79168. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  79169. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  79170. }
  79171. // Prevent zoom until bounce has completed
  79172. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  79173. this._attachedCamera.wheelPrecision = Infinity;
  79174. this._attachedCamera.inertialRadiusOffset = 0;
  79175. // Animate to the radius limit
  79176. this.stopAllAnimations();
  79177. this._radiusIsAnimating = true;
  79178. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  79179. if (animatable) {
  79180. this._animatables.push(animatable);
  79181. }
  79182. };
  79183. /**
  79184. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  79185. */
  79186. BouncingBehavior.prototype._clearAnimationLocks = function () {
  79187. this._radiusIsAnimating = false;
  79188. if (this._attachedCamera) {
  79189. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  79190. }
  79191. };
  79192. /**
  79193. * Stops and removes all animations that have been applied to the camera
  79194. */
  79195. BouncingBehavior.prototype.stopAllAnimations = function () {
  79196. if (this._attachedCamera) {
  79197. this._attachedCamera.animations = [];
  79198. }
  79199. while (this._animatables.length) {
  79200. this._animatables[0].onAnimationEnd = null;
  79201. this._animatables[0].stop();
  79202. this._animatables.shift();
  79203. }
  79204. };
  79205. /**
  79206. * The easing function used by animations
  79207. */
  79208. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  79209. /**
  79210. * The easing mode used by animations
  79211. */
  79212. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  79213. return BouncingBehavior;
  79214. }());
  79215. BABYLON.BouncingBehavior = BouncingBehavior;
  79216. })(BABYLON || (BABYLON = {}));
  79217. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  79218. var BABYLON;
  79219. (function (BABYLON) {
  79220. var AutoRotationBehavior = /** @class */ (function () {
  79221. function AutoRotationBehavior() {
  79222. this._zoomStopsAnimation = false;
  79223. this._idleRotationSpeed = 0.05;
  79224. this._idleRotationWaitTime = 2000;
  79225. this._idleRotationSpinupTime = 2000;
  79226. this._isPointerDown = false;
  79227. this._lastFrameTime = null;
  79228. this._lastInteractionTime = -Infinity;
  79229. this._cameraRotationSpeed = 0;
  79230. this._lastFrameRadius = 0;
  79231. }
  79232. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79233. get: function () {
  79234. return "AutoRotation";
  79235. },
  79236. enumerable: true,
  79237. configurable: true
  79238. });
  79239. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79240. /**
  79241. * Gets the flag that indicates if user zooming should stop animation.
  79242. */
  79243. get: function () {
  79244. return this._zoomStopsAnimation;
  79245. },
  79246. /**
  79247. * Sets the flag that indicates if user zooming should stop animation.
  79248. */
  79249. set: function (flag) {
  79250. this._zoomStopsAnimation = flag;
  79251. },
  79252. enumerable: true,
  79253. configurable: true
  79254. });
  79255. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79256. /**
  79257. * Gets the default speed at which the camera rotates around the model.
  79258. */
  79259. get: function () {
  79260. return this._idleRotationSpeed;
  79261. },
  79262. /**
  79263. * Sets the default speed at which the camera rotates around the model.
  79264. */
  79265. set: function (speed) {
  79266. this._idleRotationSpeed = speed;
  79267. },
  79268. enumerable: true,
  79269. configurable: true
  79270. });
  79271. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79272. /**
  79273. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79274. */
  79275. get: function () {
  79276. return this._idleRotationWaitTime;
  79277. },
  79278. /**
  79279. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79280. */
  79281. set: function (time) {
  79282. this._idleRotationWaitTime = time;
  79283. },
  79284. enumerable: true,
  79285. configurable: true
  79286. });
  79287. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79288. /**
  79289. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79290. */
  79291. get: function () {
  79292. return this._idleRotationSpinupTime;
  79293. },
  79294. /**
  79295. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79296. */
  79297. set: function (time) {
  79298. this._idleRotationSpinupTime = time;
  79299. },
  79300. enumerable: true,
  79301. configurable: true
  79302. });
  79303. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79304. /**
  79305. * Gets a value indicating if the camera is currently rotating because of this behavior
  79306. */
  79307. get: function () {
  79308. return Math.abs(this._cameraRotationSpeed) > 0;
  79309. },
  79310. enumerable: true,
  79311. configurable: true
  79312. });
  79313. AutoRotationBehavior.prototype.init = function () {
  79314. // Do notihng
  79315. };
  79316. AutoRotationBehavior.prototype.attach = function (camera) {
  79317. var _this = this;
  79318. this._attachedCamera = camera;
  79319. var scene = this._attachedCamera.getScene();
  79320. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79321. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79322. _this._isPointerDown = true;
  79323. return;
  79324. }
  79325. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79326. _this._isPointerDown = false;
  79327. }
  79328. });
  79329. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79330. var now = BABYLON.Tools.Now;
  79331. var dt = 0;
  79332. if (_this._lastFrameTime != null) {
  79333. dt = now - _this._lastFrameTime;
  79334. }
  79335. _this._lastFrameTime = now;
  79336. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79337. _this._applyUserInteraction();
  79338. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79339. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79340. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79341. // Step camera rotation by rotation speed
  79342. if (_this._attachedCamera) {
  79343. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79344. }
  79345. });
  79346. };
  79347. AutoRotationBehavior.prototype.detach = function () {
  79348. if (!this._attachedCamera) {
  79349. return;
  79350. }
  79351. var scene = this._attachedCamera.getScene();
  79352. if (this._onPrePointerObservableObserver) {
  79353. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79354. }
  79355. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79356. this._attachedCamera = null;
  79357. };
  79358. /**
  79359. * Returns true if user is scrolling.
  79360. * @return true if user is scrolling.
  79361. */
  79362. AutoRotationBehavior.prototype._userIsZooming = function () {
  79363. if (!this._attachedCamera) {
  79364. return false;
  79365. }
  79366. return this._attachedCamera.inertialRadiusOffset !== 0;
  79367. };
  79368. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79369. if (!this._attachedCamera) {
  79370. return false;
  79371. }
  79372. var zoomHasHitLimit = false;
  79373. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79374. zoomHasHitLimit = true;
  79375. }
  79376. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79377. this._lastFrameRadius = this._attachedCamera.radius;
  79378. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79379. };
  79380. /**
  79381. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79382. */
  79383. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79384. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79385. this._lastInteractionTime = BABYLON.Tools.Now;
  79386. }
  79387. };
  79388. // Tools
  79389. AutoRotationBehavior.prototype._userIsMoving = function () {
  79390. if (!this._attachedCamera) {
  79391. return false;
  79392. }
  79393. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79394. this._attachedCamera.inertialBetaOffset !== 0 ||
  79395. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79396. this._attachedCamera.inertialPanningX !== 0 ||
  79397. this._attachedCamera.inertialPanningY !== 0 ||
  79398. this._isPointerDown;
  79399. };
  79400. return AutoRotationBehavior;
  79401. }());
  79402. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79403. })(BABYLON || (BABYLON = {}));
  79404. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79405. var BABYLON;
  79406. (function (BABYLON) {
  79407. /**
  79408. * This class can be used to get instrumentation data from a Babylon engine
  79409. */
  79410. var EngineInstrumentation = /** @class */ (function () {
  79411. function EngineInstrumentation(engine) {
  79412. this.engine = engine;
  79413. this._captureGPUFrameTime = false;
  79414. this._gpuFrameTime = new BABYLON.PerfCounter();
  79415. this._captureShaderCompilationTime = false;
  79416. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79417. // Observers
  79418. this._onBeginFrameObserver = null;
  79419. this._onEndFrameObserver = null;
  79420. this._onBeforeShaderCompilationObserver = null;
  79421. this._onAfterShaderCompilationObserver = null;
  79422. }
  79423. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79424. // Properties
  79425. /**
  79426. * Gets the perf counter used for GPU frame time
  79427. */
  79428. get: function () {
  79429. return this._gpuFrameTime;
  79430. },
  79431. enumerable: true,
  79432. configurable: true
  79433. });
  79434. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79435. /**
  79436. * Gets the GPU frame time capture status
  79437. */
  79438. get: function () {
  79439. return this._captureGPUFrameTime;
  79440. },
  79441. /**
  79442. * Enable or disable the GPU frame time capture
  79443. */
  79444. set: function (value) {
  79445. var _this = this;
  79446. if (value === this._captureGPUFrameTime) {
  79447. return;
  79448. }
  79449. this._captureGPUFrameTime = value;
  79450. if (value) {
  79451. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79452. if (!_this._gpuFrameTimeToken) {
  79453. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79454. }
  79455. });
  79456. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79457. if (!_this._gpuFrameTimeToken) {
  79458. return;
  79459. }
  79460. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79461. if (time > -1) {
  79462. _this._gpuFrameTimeToken = null;
  79463. _this._gpuFrameTime.fetchNewFrame();
  79464. _this._gpuFrameTime.addCount(time, true);
  79465. }
  79466. });
  79467. }
  79468. else {
  79469. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79470. this._onBeginFrameObserver = null;
  79471. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79472. this._onEndFrameObserver = null;
  79473. }
  79474. },
  79475. enumerable: true,
  79476. configurable: true
  79477. });
  79478. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79479. /**
  79480. * Gets the perf counter used for shader compilation time
  79481. */
  79482. get: function () {
  79483. return this._shaderCompilationTime;
  79484. },
  79485. enumerable: true,
  79486. configurable: true
  79487. });
  79488. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79489. /**
  79490. * Gets the shader compilation time capture status
  79491. */
  79492. get: function () {
  79493. return this._captureShaderCompilationTime;
  79494. },
  79495. /**
  79496. * Enable or disable the shader compilation time capture
  79497. */
  79498. set: function (value) {
  79499. var _this = this;
  79500. if (value === this._captureShaderCompilationTime) {
  79501. return;
  79502. }
  79503. this._captureShaderCompilationTime = value;
  79504. if (value) {
  79505. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79506. _this._shaderCompilationTime.fetchNewFrame();
  79507. _this._shaderCompilationTime.beginMonitoring();
  79508. });
  79509. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79510. _this._shaderCompilationTime.endMonitoring();
  79511. });
  79512. }
  79513. else {
  79514. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79515. this._onBeforeShaderCompilationObserver = null;
  79516. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79517. this._onAfterShaderCompilationObserver = null;
  79518. }
  79519. },
  79520. enumerable: true,
  79521. configurable: true
  79522. });
  79523. EngineInstrumentation.prototype.dispose = function () {
  79524. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79525. this._onBeginFrameObserver = null;
  79526. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79527. this._onEndFrameObserver = null;
  79528. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79529. this._onBeforeShaderCompilationObserver = null;
  79530. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79531. this._onAfterShaderCompilationObserver = null;
  79532. this.engine = null;
  79533. };
  79534. return EngineInstrumentation;
  79535. }());
  79536. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79537. })(BABYLON || (BABYLON = {}));
  79538. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79539. var BABYLON;
  79540. (function (BABYLON) {
  79541. /**
  79542. * This class can be used to get instrumentation data from a Babylon engine
  79543. */
  79544. var SceneInstrumentation = /** @class */ (function () {
  79545. function SceneInstrumentation(scene) {
  79546. var _this = this;
  79547. this.scene = scene;
  79548. this._captureActiveMeshesEvaluationTime = false;
  79549. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79550. this._captureRenderTargetsRenderTime = false;
  79551. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79552. this._captureFrameTime = false;
  79553. this._frameTime = new BABYLON.PerfCounter();
  79554. this._captureRenderTime = false;
  79555. this._renderTime = new BABYLON.PerfCounter();
  79556. this._captureInterFrameTime = false;
  79557. this._interFrameTime = new BABYLON.PerfCounter();
  79558. this._captureParticlesRenderTime = false;
  79559. this._particlesRenderTime = new BABYLON.PerfCounter();
  79560. this._captureSpritesRenderTime = false;
  79561. this._spritesRenderTime = new BABYLON.PerfCounter();
  79562. this._capturePhysicsTime = false;
  79563. this._physicsTime = new BABYLON.PerfCounter();
  79564. this._captureAnimationsTime = false;
  79565. this._animationsTime = new BABYLON.PerfCounter();
  79566. // Observers
  79567. this._onBeforeActiveMeshesEvaluationObserver = null;
  79568. this._onAfterActiveMeshesEvaluationObserver = null;
  79569. this._onBeforeRenderTargetsRenderObserver = null;
  79570. this._onAfterRenderTargetsRenderObserver = null;
  79571. this._onAfterRenderObserver = null;
  79572. this._onBeforeDrawPhaseObserver = null;
  79573. this._onAfterDrawPhaseObserver = null;
  79574. this._onBeforeAnimationsObserver = null;
  79575. this._onBeforeParticlesRenderingObserver = null;
  79576. this._onAfterParticlesRenderingObserver = null;
  79577. this._onBeforeSpritesRenderingObserver = null;
  79578. this._onAfterSpritesRenderingObserver = null;
  79579. this._onBeforePhysicsObserver = null;
  79580. this._onAfterPhysicsObserver = null;
  79581. this._onAfterAnimationsObserver = null;
  79582. // Before render
  79583. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79584. if (_this._captureActiveMeshesEvaluationTime) {
  79585. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79586. }
  79587. if (_this._captureRenderTargetsRenderTime) {
  79588. _this._renderTargetsRenderTime.fetchNewFrame();
  79589. }
  79590. if (_this._captureFrameTime) {
  79591. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79592. _this._frameTime.beginMonitoring();
  79593. }
  79594. if (_this._captureInterFrameTime) {
  79595. _this._interFrameTime.endMonitoring();
  79596. }
  79597. if (_this._captureParticlesRenderTime) {
  79598. _this._particlesRenderTime.fetchNewFrame();
  79599. }
  79600. if (_this._captureSpritesRenderTime) {
  79601. _this._spritesRenderTime.fetchNewFrame();
  79602. }
  79603. if (_this._captureAnimationsTime) {
  79604. _this._animationsTime.beginMonitoring();
  79605. }
  79606. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79607. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79608. });
  79609. // After render
  79610. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79611. if (_this._captureFrameTime) {
  79612. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79613. _this._frameTime.endMonitoring();
  79614. }
  79615. if (_this._captureRenderTime) {
  79616. _this._renderTime.endMonitoring(false);
  79617. }
  79618. if (_this._captureInterFrameTime) {
  79619. _this._interFrameTime.beginMonitoring();
  79620. }
  79621. });
  79622. }
  79623. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79624. // Properties
  79625. /**
  79626. * Gets the perf counter used for active meshes evaluation time
  79627. */
  79628. get: function () {
  79629. return this._activeMeshesEvaluationTime;
  79630. },
  79631. enumerable: true,
  79632. configurable: true
  79633. });
  79634. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79635. /**
  79636. * Gets the active meshes evaluation time capture status
  79637. */
  79638. get: function () {
  79639. return this._captureActiveMeshesEvaluationTime;
  79640. },
  79641. /**
  79642. * Enable or disable the active meshes evaluation time capture
  79643. */
  79644. set: function (value) {
  79645. var _this = this;
  79646. if (value === this._captureActiveMeshesEvaluationTime) {
  79647. return;
  79648. }
  79649. this._captureActiveMeshesEvaluationTime = value;
  79650. if (value) {
  79651. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79652. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79653. _this._activeMeshesEvaluationTime.beginMonitoring();
  79654. });
  79655. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79656. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79657. _this._activeMeshesEvaluationTime.endMonitoring();
  79658. });
  79659. }
  79660. else {
  79661. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79662. this._onBeforeActiveMeshesEvaluationObserver = null;
  79663. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79664. this._onAfterActiveMeshesEvaluationObserver = null;
  79665. }
  79666. },
  79667. enumerable: true,
  79668. configurable: true
  79669. });
  79670. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79671. /**
  79672. * Gets the perf counter used for render targets render time
  79673. */
  79674. get: function () {
  79675. return this._renderTargetsRenderTime;
  79676. },
  79677. enumerable: true,
  79678. configurable: true
  79679. });
  79680. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79681. /**
  79682. * Gets the render targets render time capture status
  79683. */
  79684. get: function () {
  79685. return this._captureRenderTargetsRenderTime;
  79686. },
  79687. /**
  79688. * Enable or disable the render targets render time capture
  79689. */
  79690. set: function (value) {
  79691. var _this = this;
  79692. if (value === this._captureRenderTargetsRenderTime) {
  79693. return;
  79694. }
  79695. this._captureRenderTargetsRenderTime = value;
  79696. if (value) {
  79697. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79698. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79699. _this._renderTargetsRenderTime.beginMonitoring();
  79700. });
  79701. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79702. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79703. _this._renderTargetsRenderTime.endMonitoring(false);
  79704. });
  79705. }
  79706. else {
  79707. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79708. this._onBeforeRenderTargetsRenderObserver = null;
  79709. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79710. this._onAfterRenderTargetsRenderObserver = null;
  79711. }
  79712. },
  79713. enumerable: true,
  79714. configurable: true
  79715. });
  79716. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79717. /**
  79718. * Gets the perf counter used for particles render time
  79719. */
  79720. get: function () {
  79721. return this._particlesRenderTime;
  79722. },
  79723. enumerable: true,
  79724. configurable: true
  79725. });
  79726. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79727. /**
  79728. * Gets the particles render time capture status
  79729. */
  79730. get: function () {
  79731. return this._captureParticlesRenderTime;
  79732. },
  79733. /**
  79734. * Enable or disable the particles render time capture
  79735. */
  79736. set: function (value) {
  79737. var _this = this;
  79738. if (value === this._captureParticlesRenderTime) {
  79739. return;
  79740. }
  79741. this._captureParticlesRenderTime = value;
  79742. if (value) {
  79743. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79744. BABYLON.Tools.StartPerformanceCounter("Particles");
  79745. _this._particlesRenderTime.beginMonitoring();
  79746. });
  79747. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79748. BABYLON.Tools.EndPerformanceCounter("Particles");
  79749. _this._particlesRenderTime.endMonitoring(false);
  79750. });
  79751. }
  79752. else {
  79753. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79754. this._onBeforeParticlesRenderingObserver = null;
  79755. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79756. this._onAfterParticlesRenderingObserver = null;
  79757. }
  79758. },
  79759. enumerable: true,
  79760. configurable: true
  79761. });
  79762. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79763. /**
  79764. * Gets the perf counter used for sprites render time
  79765. */
  79766. get: function () {
  79767. return this._spritesRenderTime;
  79768. },
  79769. enumerable: true,
  79770. configurable: true
  79771. });
  79772. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79773. /**
  79774. * Gets the sprites render time capture status
  79775. */
  79776. get: function () {
  79777. return this._captureSpritesRenderTime;
  79778. },
  79779. /**
  79780. * Enable or disable the sprites render time capture
  79781. */
  79782. set: function (value) {
  79783. var _this = this;
  79784. if (value === this._captureSpritesRenderTime) {
  79785. return;
  79786. }
  79787. this._captureSpritesRenderTime = value;
  79788. if (value) {
  79789. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79790. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79791. _this._spritesRenderTime.beginMonitoring();
  79792. });
  79793. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79794. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79795. _this._spritesRenderTime.endMonitoring(false);
  79796. });
  79797. }
  79798. else {
  79799. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79800. this._onBeforeSpritesRenderingObserver = null;
  79801. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79802. this._onAfterSpritesRenderingObserver = null;
  79803. }
  79804. },
  79805. enumerable: true,
  79806. configurable: true
  79807. });
  79808. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  79809. /**
  79810. * Gets the perf counter used for physics time
  79811. */
  79812. get: function () {
  79813. return this._physicsTime;
  79814. },
  79815. enumerable: true,
  79816. configurable: true
  79817. });
  79818. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  79819. /**
  79820. * Gets the physics time capture status
  79821. */
  79822. get: function () {
  79823. return this._capturePhysicsTime;
  79824. },
  79825. /**
  79826. * Enable or disable the physics time capture
  79827. */
  79828. set: function (value) {
  79829. var _this = this;
  79830. if (value === this._capturePhysicsTime) {
  79831. return;
  79832. }
  79833. this._capturePhysicsTime = value;
  79834. if (value) {
  79835. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  79836. BABYLON.Tools.StartPerformanceCounter("Physics");
  79837. _this._physicsTime.beginMonitoring();
  79838. });
  79839. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  79840. BABYLON.Tools.EndPerformanceCounter("Physics");
  79841. _this._physicsTime.endMonitoring();
  79842. });
  79843. }
  79844. else {
  79845. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79846. this._onBeforePhysicsObserver = null;
  79847. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79848. this._onAfterPhysicsObserver = null;
  79849. }
  79850. },
  79851. enumerable: true,
  79852. configurable: true
  79853. });
  79854. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  79855. /**
  79856. * Gets the perf counter used for animations time
  79857. */
  79858. get: function () {
  79859. return this._animationsTime;
  79860. },
  79861. enumerable: true,
  79862. configurable: true
  79863. });
  79864. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  79865. /**
  79866. * Gets the animations time capture status
  79867. */
  79868. get: function () {
  79869. return this._captureAnimationsTime;
  79870. },
  79871. /**
  79872. * Enable or disable the animations time capture
  79873. */
  79874. set: function (value) {
  79875. var _this = this;
  79876. if (value === this._captureAnimationsTime) {
  79877. return;
  79878. }
  79879. this._captureAnimationsTime = value;
  79880. if (value) {
  79881. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  79882. _this._animationsTime.endMonitoring();
  79883. });
  79884. }
  79885. else {
  79886. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79887. this._onAfterAnimationsObserver = null;
  79888. }
  79889. },
  79890. enumerable: true,
  79891. configurable: true
  79892. });
  79893. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  79894. /**
  79895. * Gets the perf counter used for frame time capture
  79896. */
  79897. get: function () {
  79898. return this._frameTime;
  79899. },
  79900. enumerable: true,
  79901. configurable: true
  79902. });
  79903. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  79904. /**
  79905. * Gets the frame time capture status
  79906. */
  79907. get: function () {
  79908. return this._captureFrameTime;
  79909. },
  79910. /**
  79911. * Enable or disable the frame time capture
  79912. */
  79913. set: function (value) {
  79914. this._captureFrameTime = value;
  79915. },
  79916. enumerable: true,
  79917. configurable: true
  79918. });
  79919. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  79920. /**
  79921. * Gets the perf counter used for inter-frames time capture
  79922. */
  79923. get: function () {
  79924. return this._interFrameTime;
  79925. },
  79926. enumerable: true,
  79927. configurable: true
  79928. });
  79929. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  79930. /**
  79931. * Gets the inter-frames time capture status
  79932. */
  79933. get: function () {
  79934. return this._captureInterFrameTime;
  79935. },
  79936. /**
  79937. * Enable or disable the inter-frames time capture
  79938. */
  79939. set: function (value) {
  79940. this._captureInterFrameTime = value;
  79941. },
  79942. enumerable: true,
  79943. configurable: true
  79944. });
  79945. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  79946. /**
  79947. * Gets the perf counter used for render time capture
  79948. */
  79949. get: function () {
  79950. return this._renderTime;
  79951. },
  79952. enumerable: true,
  79953. configurable: true
  79954. });
  79955. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  79956. /**
  79957. * Gets the render time capture status
  79958. */
  79959. get: function () {
  79960. return this._captureRenderTime;
  79961. },
  79962. /**
  79963. * Enable or disable the render time capture
  79964. */
  79965. set: function (value) {
  79966. var _this = this;
  79967. if (value === this._captureRenderTime) {
  79968. return;
  79969. }
  79970. this._captureRenderTime = value;
  79971. if (value) {
  79972. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  79973. _this._renderTime.beginMonitoring();
  79974. BABYLON.Tools.StartPerformanceCounter("Main render");
  79975. });
  79976. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  79977. _this._renderTime.endMonitoring(false);
  79978. BABYLON.Tools.EndPerformanceCounter("Main render");
  79979. });
  79980. }
  79981. else {
  79982. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79983. this._onBeforeDrawPhaseObserver = null;
  79984. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79985. this._onAfterDrawPhaseObserver = null;
  79986. }
  79987. },
  79988. enumerable: true,
  79989. configurable: true
  79990. });
  79991. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  79992. /**
  79993. * Gets the perf counter used for draw calls
  79994. */
  79995. get: function () {
  79996. return this.scene.getEngine()._drawCalls;
  79997. },
  79998. enumerable: true,
  79999. configurable: true
  80000. });
  80001. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80002. /**
  80003. * Gets the perf counter used for texture collisions
  80004. */
  80005. get: function () {
  80006. return this.scene.getEngine()._textureCollisions;
  80007. },
  80008. enumerable: true,
  80009. configurable: true
  80010. });
  80011. SceneInstrumentation.prototype.dispose = function () {
  80012. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80013. this._onAfterRenderObserver = null;
  80014. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80015. this._onBeforeActiveMeshesEvaluationObserver = null;
  80016. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80017. this._onAfterActiveMeshesEvaluationObserver = null;
  80018. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80019. this._onBeforeRenderTargetsRenderObserver = null;
  80020. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80021. this._onAfterRenderTargetsRenderObserver = null;
  80022. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80023. this._onBeforeAnimationsObserver = null;
  80024. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80025. this._onBeforeParticlesRenderingObserver = null;
  80026. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80027. this._onAfterParticlesRenderingObserver = null;
  80028. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80029. this._onBeforeSpritesRenderingObserver = null;
  80030. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80031. this._onAfterSpritesRenderingObserver = null;
  80032. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80033. this._onBeforeDrawPhaseObserver = null;
  80034. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80035. this._onAfterDrawPhaseObserver = null;
  80036. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80037. this._onBeforePhysicsObserver = null;
  80038. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80039. this._onAfterPhysicsObserver = null;
  80040. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80041. this._onAfterAnimationsObserver = null;
  80042. this.scene = null;
  80043. };
  80044. return SceneInstrumentation;
  80045. }());
  80046. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80047. })(BABYLON || (BABYLON = {}));
  80048. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80049. var BABYLON;
  80050. (function (BABYLON) {
  80051. var _TimeToken = /** @class */ (function () {
  80052. function _TimeToken() {
  80053. this._timeElapsedQueryEnded = false;
  80054. }
  80055. return _TimeToken;
  80056. }());
  80057. BABYLON._TimeToken = _TimeToken;
  80058. })(BABYLON || (BABYLON = {}));
  80059. //# sourceMappingURL=babylon.timeToken.js.map
  80060. var BABYLON;
  80061. (function (BABYLON) {
  80062. /**
  80063. * Background material defines definition.
  80064. */
  80065. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80066. __extends(BackgroundMaterialDefines, _super);
  80067. /**
  80068. * Constructor of the defines.
  80069. */
  80070. function BackgroundMaterialDefines() {
  80071. var _this = _super.call(this) || this;
  80072. /**
  80073. * True if the diffuse texture is in use.
  80074. */
  80075. _this.DIFFUSE = false;
  80076. /**
  80077. * The direct UV channel to use.
  80078. */
  80079. _this.DIFFUSEDIRECTUV = 0;
  80080. /**
  80081. * True if the diffuse texture is in gamma space.
  80082. */
  80083. _this.GAMMADIFFUSE = false;
  80084. /**
  80085. * True if the diffuse texture has opacity in the alpha channel.
  80086. */
  80087. _this.DIFFUSEHASALPHA = false;
  80088. /**
  80089. * True if you want the material to fade to transparent at grazing angle.
  80090. */
  80091. _this.OPACITYFRESNEL = false;
  80092. /**
  80093. * True if an extra blur needs to be added in the reflection.
  80094. */
  80095. _this.REFLECTIONBLUR = false;
  80096. /**
  80097. * True if you want the material to fade to reflection at grazing angle.
  80098. */
  80099. _this.REFLECTIONFRESNEL = false;
  80100. /**
  80101. * True if you want the material to falloff as far as you move away from the scene center.
  80102. */
  80103. _this.REFLECTIONFALLOFF = false;
  80104. /**
  80105. * False if the current Webgl implementation does not support the texture lod extension.
  80106. */
  80107. _this.TEXTURELODSUPPORT = false;
  80108. /**
  80109. * True to ensure the data are premultiplied.
  80110. */
  80111. _this.PREMULTIPLYALPHA = false;
  80112. /**
  80113. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80114. */
  80115. _this.USERGBCOLOR = false;
  80116. /**
  80117. * True to add noise in order to reduce the banding effect.
  80118. */
  80119. _this.NOISE = false;
  80120. // Image Processing Configuration.
  80121. _this.IMAGEPROCESSING = false;
  80122. _this.VIGNETTE = false;
  80123. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80124. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80125. _this.TONEMAPPING = false;
  80126. _this.CONTRAST = false;
  80127. _this.COLORCURVES = false;
  80128. _this.COLORGRADING = false;
  80129. _this.COLORGRADING3D = false;
  80130. _this.SAMPLER3DGREENDEPTH = false;
  80131. _this.SAMPLER3DBGRMAP = false;
  80132. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80133. _this.EXPOSURE = false;
  80134. // Reflection.
  80135. _this.REFLECTION = false;
  80136. _this.REFLECTIONMAP_3D = false;
  80137. _this.REFLECTIONMAP_SPHERICAL = false;
  80138. _this.REFLECTIONMAP_PLANAR = false;
  80139. _this.REFLECTIONMAP_CUBIC = false;
  80140. _this.REFLECTIONMAP_PROJECTION = false;
  80141. _this.REFLECTIONMAP_SKYBOX = false;
  80142. _this.REFLECTIONMAP_EXPLICIT = false;
  80143. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80144. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80145. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80146. _this.INVERTCUBICMAP = false;
  80147. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80148. _this.LODINREFLECTIONALPHA = false;
  80149. _this.GAMMAREFLECTION = false;
  80150. // Default BJS.
  80151. _this.MAINUV1 = false;
  80152. _this.MAINUV2 = false;
  80153. _this.UV1 = false;
  80154. _this.UV2 = false;
  80155. _this.CLIPPLANE = false;
  80156. _this.POINTSIZE = false;
  80157. _this.FOG = false;
  80158. _this.NORMAL = false;
  80159. _this.NUM_BONE_INFLUENCERS = 0;
  80160. _this.BonesPerMesh = 0;
  80161. _this.INSTANCES = false;
  80162. _this.SHADOWFLOAT = false;
  80163. _this.rebuild();
  80164. return _this;
  80165. }
  80166. return BackgroundMaterialDefines;
  80167. }(BABYLON.MaterialDefines));
  80168. /**
  80169. * Background material used to create an efficient environement around your scene.
  80170. */
  80171. var BackgroundMaterial = /** @class */ (function (_super) {
  80172. __extends(BackgroundMaterial, _super);
  80173. /**
  80174. * constructor
  80175. * @param name The name of the material
  80176. * @param scene The scene to add the material to
  80177. */
  80178. function BackgroundMaterial(name, scene) {
  80179. var _this = _super.call(this, name, scene) || this;
  80180. _this.primaryColor = BABYLON.Color3.White();
  80181. _this.primaryLevel = 1;
  80182. _this.secondaryColor = BABYLON.Color3.Gray();
  80183. _this.secondaryLevel = 1;
  80184. _this.tertiaryColor = BABYLON.Color3.Black();
  80185. _this.tertiaryLevel = 1;
  80186. _this.reflectionTexture = null;
  80187. _this.reflectionBlur = 0;
  80188. _this.diffuseTexture = null;
  80189. /**
  80190. * Specify the list of lights casting shadow on the material.
  80191. * All scene shadow lights will be included if null.
  80192. */
  80193. _this._shadowLights = null;
  80194. _this.shadowLights = null;
  80195. _this.shadowBlurScale = 1;
  80196. _this.shadowLevel = 0;
  80197. _this.sceneCenter = BABYLON.Vector3.Zero();
  80198. _this.opacityFresnel = true;
  80199. _this.reflectionFresnel = false;
  80200. _this.reflectionFalloffDistance = 0.0;
  80201. _this.reflectionAmount = 1.0;
  80202. _this.reflectionReflectance0 = 0.05;
  80203. _this.reflectionReflectance90 = 0.5;
  80204. _this.useRGBColor = true;
  80205. _this.enableNoise = false;
  80206. /**
  80207. * Number of Simultaneous lights allowed on the material.
  80208. */
  80209. _this._maxSimultaneousLights = 4;
  80210. _this.maxSimultaneousLights = 4;
  80211. /**
  80212. * Keep track of the image processing observer to allow dispose and replace.
  80213. */
  80214. _this._imageProcessingObserver = null;
  80215. // Temp values kept as cache in the material.
  80216. _this._renderTargets = new BABYLON.SmartArray(16);
  80217. _this._reflectionControls = BABYLON.Vector4.Zero();
  80218. // Setup the default processing configuration to the scene.
  80219. _this._attachImageProcessingConfiguration(null);
  80220. _this.getRenderTargetTextures = function () {
  80221. _this._renderTargets.reset();
  80222. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80223. _this._renderTargets.push(_this._diffuseTexture);
  80224. }
  80225. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80226. _this._renderTargets.push(_this._reflectionTexture);
  80227. }
  80228. return _this._renderTargets;
  80229. };
  80230. return _this;
  80231. }
  80232. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80233. /**
  80234. * Sets the reflection reflectance fresnel values according to the default standard
  80235. * empirically know to work well :-)
  80236. */
  80237. set: function (value) {
  80238. var reflectionWeight = value;
  80239. if (reflectionWeight < 0.5) {
  80240. reflectionWeight = reflectionWeight * 2.0;
  80241. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80242. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80243. }
  80244. else {
  80245. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80246. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80247. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80248. }
  80249. },
  80250. enumerable: true,
  80251. configurable: true
  80252. });
  80253. /**
  80254. * Attaches a new image processing configuration to the PBR Material.
  80255. * @param configuration (if null the scene configuration will be use)
  80256. */
  80257. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80258. var _this = this;
  80259. if (configuration === this._imageProcessingConfiguration) {
  80260. return;
  80261. }
  80262. // Detaches observer.
  80263. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80264. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80265. }
  80266. // Pick the scene configuration if needed.
  80267. if (!configuration) {
  80268. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80269. }
  80270. else {
  80271. this._imageProcessingConfiguration = configuration;
  80272. }
  80273. // Attaches observer.
  80274. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80275. _this._markAllSubMeshesAsImageProcessingDirty();
  80276. });
  80277. };
  80278. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80279. /**
  80280. * Gets the image processing configuration used either in this material.
  80281. */
  80282. get: function () {
  80283. return this._imageProcessingConfiguration;
  80284. },
  80285. /**
  80286. * Sets the Default image processing configuration used either in the this material.
  80287. *
  80288. * If sets to null, the scene one is in use.
  80289. */
  80290. set: function (value) {
  80291. this._attachImageProcessingConfiguration(value);
  80292. // Ensure the effect will be rebuilt.
  80293. this._markAllSubMeshesAsTexturesDirty();
  80294. },
  80295. enumerable: true,
  80296. configurable: true
  80297. });
  80298. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80299. /**
  80300. * Gets wether the color curves effect is enabled.
  80301. */
  80302. get: function () {
  80303. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80304. },
  80305. /**
  80306. * Sets wether the color curves effect is enabled.
  80307. */
  80308. set: function (value) {
  80309. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80310. },
  80311. enumerable: true,
  80312. configurable: true
  80313. });
  80314. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80315. /**
  80316. * Gets wether the color grading effect is enabled.
  80317. */
  80318. get: function () {
  80319. return this.imageProcessingConfiguration.colorGradingEnabled;
  80320. },
  80321. /**
  80322. * Gets wether the color grading effect is enabled.
  80323. */
  80324. set: function (value) {
  80325. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80326. },
  80327. enumerable: true,
  80328. configurable: true
  80329. });
  80330. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80331. /**
  80332. * Gets wether tonemapping is enabled or not.
  80333. */
  80334. get: function () {
  80335. return this._imageProcessingConfiguration.toneMappingEnabled;
  80336. },
  80337. /**
  80338. * Sets wether tonemapping is enabled or not
  80339. */
  80340. set: function (value) {
  80341. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80342. },
  80343. enumerable: true,
  80344. configurable: true
  80345. });
  80346. ;
  80347. ;
  80348. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80349. /**
  80350. * The camera exposure used on this material.
  80351. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80352. * This corresponds to a photographic exposure.
  80353. */
  80354. get: function () {
  80355. return this._imageProcessingConfiguration.exposure;
  80356. },
  80357. /**
  80358. * The camera exposure used on this material.
  80359. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80360. * This corresponds to a photographic exposure.
  80361. */
  80362. set: function (value) {
  80363. this._imageProcessingConfiguration.exposure = value;
  80364. },
  80365. enumerable: true,
  80366. configurable: true
  80367. });
  80368. ;
  80369. ;
  80370. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80371. /**
  80372. * Gets The camera contrast used on this material.
  80373. */
  80374. get: function () {
  80375. return this._imageProcessingConfiguration.contrast;
  80376. },
  80377. /**
  80378. * Sets The camera contrast used on this material.
  80379. */
  80380. set: function (value) {
  80381. this._imageProcessingConfiguration.contrast = value;
  80382. },
  80383. enumerable: true,
  80384. configurable: true
  80385. });
  80386. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80387. /**
  80388. * Gets the Color Grading 2D Lookup Texture.
  80389. */
  80390. get: function () {
  80391. return this._imageProcessingConfiguration.colorGradingTexture;
  80392. },
  80393. /**
  80394. * Sets the Color Grading 2D Lookup Texture.
  80395. */
  80396. set: function (value) {
  80397. this.imageProcessingConfiguration.colorGradingTexture = value;
  80398. },
  80399. enumerable: true,
  80400. configurable: true
  80401. });
  80402. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80403. /**
  80404. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80405. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80406. * 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;
  80407. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80408. */
  80409. get: function () {
  80410. return this.imageProcessingConfiguration.colorCurves;
  80411. },
  80412. /**
  80413. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80414. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80415. * 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;
  80416. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80417. */
  80418. set: function (value) {
  80419. this.imageProcessingConfiguration.colorCurves = value;
  80420. },
  80421. enumerable: true,
  80422. configurable: true
  80423. });
  80424. /**
  80425. * The entire material has been created in order to prevent overdraw.
  80426. * @returns false
  80427. */
  80428. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80429. return true;
  80430. };
  80431. /**
  80432. * The entire material has been created in order to prevent overdraw.
  80433. * @returns true if blending is enable
  80434. */
  80435. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80436. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80437. };
  80438. /**
  80439. * Checks wether the material is ready to be rendered for a given mesh.
  80440. * @param mesh The mesh to render
  80441. * @param subMesh The submesh to check against
  80442. * @param useInstances Specify wether or not the material is used with instances
  80443. */
  80444. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80445. var _this = this;
  80446. if (useInstances === void 0) { useInstances = false; }
  80447. if (subMesh.effect && this.isFrozen) {
  80448. if (this._wasPreviouslyReady) {
  80449. return true;
  80450. }
  80451. }
  80452. if (!subMesh._materialDefines) {
  80453. subMesh._materialDefines = new BackgroundMaterialDefines();
  80454. }
  80455. var scene = this.getScene();
  80456. var defines = subMesh._materialDefines;
  80457. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80458. if (defines._renderId === scene.getRenderId()) {
  80459. return true;
  80460. }
  80461. }
  80462. var engine = scene.getEngine();
  80463. // Lights
  80464. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80465. defines._needNormals = true;
  80466. // Textures
  80467. if (defines._areTexturesDirty) {
  80468. defines._needUVs = false;
  80469. if (scene.texturesEnabled) {
  80470. if (scene.getEngine().getCaps().textureLOD) {
  80471. defines.TEXTURELODSUPPORT = true;
  80472. }
  80473. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80474. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80475. return false;
  80476. }
  80477. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80478. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80479. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80480. defines.OPACITYFRESNEL = this._opacityFresnel;
  80481. }
  80482. else {
  80483. defines.DIFFUSE = false;
  80484. defines.DIFFUSEHASALPHA = false;
  80485. defines.GAMMADIFFUSE = false;
  80486. defines.OPACITYFRESNEL = false;
  80487. }
  80488. var reflectionTexture = this._reflectionTexture;
  80489. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80490. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80491. return false;
  80492. }
  80493. defines.REFLECTION = true;
  80494. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80495. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80496. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80497. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80498. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80499. defines.INVERTCUBICMAP = true;
  80500. }
  80501. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80502. switch (reflectionTexture.coordinatesMode) {
  80503. case BABYLON.Texture.CUBIC_MODE:
  80504. case BABYLON.Texture.INVCUBIC_MODE:
  80505. defines.REFLECTIONMAP_CUBIC = true;
  80506. break;
  80507. case BABYLON.Texture.EXPLICIT_MODE:
  80508. defines.REFLECTIONMAP_EXPLICIT = true;
  80509. break;
  80510. case BABYLON.Texture.PLANAR_MODE:
  80511. defines.REFLECTIONMAP_PLANAR = true;
  80512. break;
  80513. case BABYLON.Texture.PROJECTION_MODE:
  80514. defines.REFLECTIONMAP_PROJECTION = true;
  80515. break;
  80516. case BABYLON.Texture.SKYBOX_MODE:
  80517. defines.REFLECTIONMAP_SKYBOX = true;
  80518. break;
  80519. case BABYLON.Texture.SPHERICAL_MODE:
  80520. defines.REFLECTIONMAP_SPHERICAL = true;
  80521. break;
  80522. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80523. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80524. break;
  80525. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80526. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80527. break;
  80528. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80529. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80530. break;
  80531. }
  80532. if (this.reflectionFresnel) {
  80533. defines.REFLECTIONFRESNEL = true;
  80534. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80535. this._reflectionControls.x = this.reflectionAmount;
  80536. this._reflectionControls.y = this.reflectionReflectance0;
  80537. this._reflectionControls.z = this.reflectionReflectance90;
  80538. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80539. }
  80540. else {
  80541. defines.REFLECTIONFRESNEL = false;
  80542. defines.REFLECTIONFALLOFF = false;
  80543. }
  80544. }
  80545. else {
  80546. defines.REFLECTION = false;
  80547. defines.REFLECTIONFALLOFF = false;
  80548. defines.REFLECTIONBLUR = false;
  80549. defines.REFLECTIONMAP_3D = false;
  80550. defines.REFLECTIONMAP_SPHERICAL = false;
  80551. defines.REFLECTIONMAP_PLANAR = false;
  80552. defines.REFLECTIONMAP_CUBIC = false;
  80553. defines.REFLECTIONMAP_PROJECTION = false;
  80554. defines.REFLECTIONMAP_SKYBOX = false;
  80555. defines.REFLECTIONMAP_EXPLICIT = false;
  80556. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80557. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80558. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80559. defines.INVERTCUBICMAP = false;
  80560. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80561. defines.LODINREFLECTIONALPHA = false;
  80562. defines.GAMMAREFLECTION = false;
  80563. }
  80564. }
  80565. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80566. defines.USERGBCOLOR = this._useRGBColor;
  80567. defines.NOISE = this._enableNoise;
  80568. }
  80569. if (defines._areImageProcessingDirty) {
  80570. if (!this._imageProcessingConfiguration.isReady()) {
  80571. return false;
  80572. }
  80573. this._imageProcessingConfiguration.prepareDefines(defines);
  80574. }
  80575. // Misc.
  80576. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80577. // Values that need to be evaluated on every frame
  80578. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  80579. // Attribs
  80580. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80581. if (mesh) {
  80582. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80583. mesh.createNormals(true);
  80584. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80585. }
  80586. }
  80587. }
  80588. // Get correct effect
  80589. if (defines.isDirty) {
  80590. defines.markAsProcessed();
  80591. scene.resetCachedMaterial();
  80592. // Fallbacks
  80593. var fallbacks = new BABYLON.EffectFallbacks();
  80594. if (defines.FOG) {
  80595. fallbacks.addFallback(0, "FOG");
  80596. }
  80597. if (defines.POINTSIZE) {
  80598. fallbacks.addFallback(1, "POINTSIZE");
  80599. }
  80600. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80601. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80602. fallbacks.addCPUSkinningFallback(0, mesh);
  80603. }
  80604. //Attributes
  80605. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80606. if (defines.NORMAL) {
  80607. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80608. }
  80609. if (defines.UV1) {
  80610. attribs.push(BABYLON.VertexBuffer.UVKind);
  80611. }
  80612. if (defines.UV2) {
  80613. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80614. }
  80615. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80616. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80617. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80618. "vFogInfos", "vFogColor", "pointSize",
  80619. "vClipPlane", "mBones",
  80620. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80621. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80622. "shadowLevel", "alpha",
  80623. "vBackgroundCenter", "vReflectionControl",
  80624. "vDiffuseInfos", "diffuseMatrix",
  80625. ];
  80626. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80627. var uniformBuffers = ["Material", "Scene"];
  80628. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80629. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80630. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80631. uniformsNames: uniforms,
  80632. uniformBuffersNames: uniformBuffers,
  80633. samplers: samplers,
  80634. defines: defines,
  80635. maxSimultaneousLights: this._maxSimultaneousLights
  80636. });
  80637. var onCompiled = function (effect) {
  80638. if (_this.onCompiled) {
  80639. _this.onCompiled(effect);
  80640. }
  80641. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80642. };
  80643. var join = defines.toString();
  80644. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80645. attributes: attribs,
  80646. uniformsNames: uniforms,
  80647. uniformBuffersNames: uniformBuffers,
  80648. samplers: samplers,
  80649. defines: join,
  80650. fallbacks: fallbacks,
  80651. onCompiled: onCompiled,
  80652. onError: this.onError,
  80653. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80654. }, engine), defines);
  80655. this.buildUniformLayout();
  80656. }
  80657. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80658. return false;
  80659. }
  80660. defines._renderId = scene.getRenderId();
  80661. this._wasPreviouslyReady = true;
  80662. return true;
  80663. };
  80664. /**
  80665. * Build the uniform buffer used in the material.
  80666. */
  80667. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80668. // Order is important !
  80669. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80670. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80671. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80672. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80673. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80674. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80675. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80676. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80677. this._uniformBuffer.addUniform("pointSize", 1);
  80678. this._uniformBuffer.addUniform("shadowLevel", 1);
  80679. this._uniformBuffer.addUniform("alpha", 1);
  80680. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80681. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80682. this._uniformBuffer.create();
  80683. };
  80684. /**
  80685. * Unbind the material.
  80686. */
  80687. BackgroundMaterial.prototype.unbind = function () {
  80688. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80689. this._uniformBuffer.setTexture("diffuseSampler", null);
  80690. }
  80691. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80692. this._uniformBuffer.setTexture("reflectionSampler", null);
  80693. }
  80694. _super.prototype.unbind.call(this);
  80695. };
  80696. /**
  80697. * Bind only the world matrix to the material.
  80698. * @param world The world matrix to bind.
  80699. */
  80700. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80701. this._activeEffect.setMatrix("world", world);
  80702. };
  80703. /**
  80704. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80705. * @param world The world matrix to bind.
  80706. * @param subMesh The submesh to bind for.
  80707. */
  80708. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80709. var scene = this.getScene();
  80710. var defines = subMesh._materialDefines;
  80711. if (!defines) {
  80712. return;
  80713. }
  80714. var effect = subMesh.effect;
  80715. if (!effect) {
  80716. return;
  80717. }
  80718. this._activeEffect = effect;
  80719. // Matrices
  80720. this.bindOnlyWorldMatrix(world);
  80721. // Bones
  80722. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80723. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80724. if (mustRebind) {
  80725. this._uniformBuffer.bindToEffect(effect, "Material");
  80726. this.bindViewProjection(effect);
  80727. var reflectionTexture = this._reflectionTexture;
  80728. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80729. // Texture uniforms
  80730. if (scene.texturesEnabled) {
  80731. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80732. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80733. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80734. }
  80735. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80736. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80737. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80738. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80739. }
  80740. }
  80741. if (this.shadowLevel > 0) {
  80742. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80743. }
  80744. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80745. // Point size
  80746. if (this.pointsCloud) {
  80747. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80748. }
  80749. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80750. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80751. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80752. }
  80753. // Textures
  80754. if (scene.texturesEnabled) {
  80755. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80756. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80757. }
  80758. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80759. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80760. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80761. }
  80762. else if (!defines.REFLECTIONBLUR) {
  80763. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80764. }
  80765. else {
  80766. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80767. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80768. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80769. }
  80770. if (defines.REFLECTIONFRESNEL) {
  80771. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80772. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80773. }
  80774. }
  80775. }
  80776. // Clip plane
  80777. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80778. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80779. }
  80780. if (mustRebind || !this.isFrozen) {
  80781. if (scene.lightsEnabled) {
  80782. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80783. }
  80784. // View
  80785. this.bindView(effect);
  80786. // Fog
  80787. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80788. // image processing
  80789. this._imageProcessingConfiguration.bind(this._activeEffect);
  80790. }
  80791. this._uniformBuffer.update();
  80792. this._afterBind(mesh);
  80793. };
  80794. /**
  80795. * Dispose the material.
  80796. * @forceDisposeEffect Force disposal of the associated effect.
  80797. * @forceDisposeTextures Force disposal of the associated textures.
  80798. */
  80799. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80800. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80801. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80802. if (forceDisposeTextures) {
  80803. if (this.diffuseTexture) {
  80804. this.diffuseTexture.dispose();
  80805. }
  80806. if (this.reflectionTexture) {
  80807. this.reflectionTexture.dispose();
  80808. }
  80809. }
  80810. this._renderTargets.dispose();
  80811. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80812. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80813. }
  80814. _super.prototype.dispose.call(this, forceDisposeEffect);
  80815. };
  80816. /**
  80817. * Clones the material.
  80818. * @name The cloned name.
  80819. * @returns The cloned material.
  80820. */
  80821. BackgroundMaterial.prototype.clone = function (name) {
  80822. var _this = this;
  80823. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  80824. };
  80825. /**
  80826. * Serializes the current material to its JSON representation.
  80827. * @returns The JSON representation.
  80828. */
  80829. BackgroundMaterial.prototype.serialize = function () {
  80830. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80831. serializationObject.customType = "BABYLON.BackgroundMaterial";
  80832. return serializationObject;
  80833. };
  80834. /**
  80835. * Gets the class name of the material
  80836. * @returns "BackgroundMaterial"
  80837. */
  80838. BackgroundMaterial.prototype.getClassName = function () {
  80839. return "BackgroundMaterial";
  80840. };
  80841. /**
  80842. * Parse a JSON input to create back a background material.
  80843. * @param source
  80844. * @param scene
  80845. * @param rootUrl
  80846. * @returns the instantiated BackgroundMaterial.
  80847. */
  80848. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  80849. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  80850. };
  80851. /**
  80852. * Standard reflectance value at parallel view angle.
  80853. */
  80854. BackgroundMaterial.standardReflectance0 = 0.05;
  80855. /**
  80856. * Standard reflectance value at grazing angle.
  80857. */
  80858. BackgroundMaterial.standardReflectance90 = 0.5;
  80859. __decorate([
  80860. BABYLON.serializeAsColor3()
  80861. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  80862. __decorate([
  80863. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80864. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  80865. __decorate([
  80866. BABYLON.serialize()
  80867. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  80868. __decorate([
  80869. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80870. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  80871. __decorate([
  80872. BABYLON.serializeAsColor3()
  80873. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  80874. __decorate([
  80875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80876. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  80877. __decorate([
  80878. BABYLON.serialize()
  80879. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  80880. __decorate([
  80881. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80882. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  80883. __decorate([
  80884. BABYLON.serializeAsColor3()
  80885. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  80886. __decorate([
  80887. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80888. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  80889. __decorate([
  80890. BABYLON.serialize()
  80891. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  80892. __decorate([
  80893. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80894. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  80895. __decorate([
  80896. BABYLON.serializeAsTexture()
  80897. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  80898. __decorate([
  80899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80900. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  80901. __decorate([
  80902. BABYLON.serialize()
  80903. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  80904. __decorate([
  80905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80906. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  80907. __decorate([
  80908. BABYLON.serializeAsTexture()
  80909. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  80910. __decorate([
  80911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80912. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  80913. __decorate([
  80914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80915. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  80916. __decorate([
  80917. BABYLON.serialize()
  80918. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  80919. __decorate([
  80920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80921. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  80922. __decorate([
  80923. BABYLON.serialize()
  80924. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  80925. __decorate([
  80926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80927. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  80928. __decorate([
  80929. BABYLON.serializeAsVector3()
  80930. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  80931. __decorate([
  80932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80933. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  80934. __decorate([
  80935. BABYLON.serialize()
  80936. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  80937. __decorate([
  80938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80939. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  80940. __decorate([
  80941. BABYLON.serialize()
  80942. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  80943. __decorate([
  80944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80945. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  80946. __decorate([
  80947. BABYLON.serialize()
  80948. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  80949. __decorate([
  80950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80951. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  80952. __decorate([
  80953. BABYLON.serialize()
  80954. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  80955. __decorate([
  80956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80957. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  80958. __decorate([
  80959. BABYLON.serialize()
  80960. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  80961. __decorate([
  80962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80963. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  80964. __decorate([
  80965. BABYLON.serialize()
  80966. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  80967. __decorate([
  80968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80969. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  80970. __decorate([
  80971. BABYLON.serialize()
  80972. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  80973. __decorate([
  80974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80975. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  80976. __decorate([
  80977. BABYLON.serialize()
  80978. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  80979. __decorate([
  80980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80981. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  80982. __decorate([
  80983. BABYLON.serialize()
  80984. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  80985. __decorate([
  80986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80987. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  80988. __decorate([
  80989. BABYLON.serializeAsImageProcessingConfiguration()
  80990. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  80991. return BackgroundMaterial;
  80992. }(BABYLON.PushMaterial));
  80993. BABYLON.BackgroundMaterial = BackgroundMaterial;
  80994. })(BABYLON || (BABYLON = {}));
  80995. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  80996. var __assign = (this && this.__assign) || Object.assign || function(t) {
  80997. for (var s, i = 1, n = arguments.length; i < n; i++) {
  80998. s = arguments[i];
  80999. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81000. t[p] = s[p];
  81001. }
  81002. return t;
  81003. };
  81004. var BABYLON;
  81005. (function (BABYLON) {
  81006. /**
  81007. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81008. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81009. * It also helps with the default setup of your imageProcessing configuration.
  81010. */
  81011. var EnvironmentHelper = /** @class */ (function () {
  81012. /**
  81013. * constructor
  81014. * @param options
  81015. * @param scene The scene to add the material to
  81016. */
  81017. function EnvironmentHelper(options, scene) {
  81018. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81019. this._scene = scene;
  81020. this._setupBackground();
  81021. this._setupImageProcessing();
  81022. }
  81023. /**
  81024. * Creates the default options for the helper.
  81025. */
  81026. EnvironmentHelper._getDefaultOptions = function () {
  81027. return {
  81028. createGround: true,
  81029. groundSize: 15,
  81030. groundTexture: this._groundTextureCDNUrl,
  81031. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81032. groundOpacity: 0.9,
  81033. enableGroundShadow: true,
  81034. groundShadowLevel: 0.5,
  81035. enableGroundMirror: false,
  81036. groundMirrorSizeRatio: 0.3,
  81037. groundMirrorBlurKernel: 64,
  81038. groundMirrorAmount: 1,
  81039. groundMirrorFresnelWeight: 1,
  81040. groundMirrorFallOffDistance: 0,
  81041. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81042. groundYBias: 0.00001,
  81043. createSkybox: true,
  81044. skyboxSize: 20,
  81045. skyboxTexture: this._skyboxTextureCDNUrl,
  81046. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81047. backgroundYRotation: 0,
  81048. sizeAuto: true,
  81049. rootPosition: BABYLON.Vector3.Zero(),
  81050. setupImageProcessing: true,
  81051. environmentTexture: this._environmentTextureCDNUrl,
  81052. cameraExposure: 0.8,
  81053. cameraContrast: 1.2,
  81054. toneMappingEnabled: true,
  81055. };
  81056. };
  81057. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81058. /**
  81059. * Gets the root mesh created by the helper.
  81060. */
  81061. get: function () {
  81062. return this._rootMesh;
  81063. },
  81064. enumerable: true,
  81065. configurable: true
  81066. });
  81067. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81068. /**
  81069. * Gets the skybox created by the helper.
  81070. */
  81071. get: function () {
  81072. return this._skybox;
  81073. },
  81074. enumerable: true,
  81075. configurable: true
  81076. });
  81077. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81078. /**
  81079. * Gets the skybox texture created by the helper.
  81080. */
  81081. get: function () {
  81082. return this._skyboxTexture;
  81083. },
  81084. enumerable: true,
  81085. configurable: true
  81086. });
  81087. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81088. /**
  81089. * Gets the skybox material created by the helper.
  81090. */
  81091. get: function () {
  81092. return this._skyboxMaterial;
  81093. },
  81094. enumerable: true,
  81095. configurable: true
  81096. });
  81097. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81098. /**
  81099. * Gets the ground mesh created by the helper.
  81100. */
  81101. get: function () {
  81102. return this._ground;
  81103. },
  81104. enumerable: true,
  81105. configurable: true
  81106. });
  81107. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81108. /**
  81109. * Gets the ground texture created by the helper.
  81110. */
  81111. get: function () {
  81112. return this._groundTexture;
  81113. },
  81114. enumerable: true,
  81115. configurable: true
  81116. });
  81117. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81118. /**
  81119. * Gets the ground mirror created by the helper.
  81120. */
  81121. get: function () {
  81122. return this._groundMirror;
  81123. },
  81124. enumerable: true,
  81125. configurable: true
  81126. });
  81127. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81128. /**
  81129. * Gets the ground mirror render list to helps pushing the meshes
  81130. * you wish in the ground reflection.
  81131. */
  81132. get: function () {
  81133. if (this._groundMirror) {
  81134. return this._groundMirror.renderList;
  81135. }
  81136. return null;
  81137. },
  81138. enumerable: true,
  81139. configurable: true
  81140. });
  81141. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81142. /**
  81143. * Gets the ground material created by the helper.
  81144. */
  81145. get: function () {
  81146. return this._groundMaterial;
  81147. },
  81148. enumerable: true,
  81149. configurable: true
  81150. });
  81151. /**
  81152. * Updates the background according to the new options
  81153. * @param options
  81154. */
  81155. EnvironmentHelper.prototype.updateOptions = function (options) {
  81156. var newOptions = __assign({}, this._options, options);
  81157. if (this._ground && !newOptions.createGround) {
  81158. this._ground.dispose();
  81159. this._ground = null;
  81160. }
  81161. if (this._groundMaterial && !newOptions.createGround) {
  81162. this._groundMaterial.dispose();
  81163. this._groundMaterial = null;
  81164. }
  81165. if (this._groundTexture) {
  81166. if (this._options.groundTexture != newOptions.groundTexture) {
  81167. this._groundTexture.dispose();
  81168. this._groundTexture = null;
  81169. }
  81170. }
  81171. if (this._skybox && !newOptions.createSkybox) {
  81172. this._skybox.dispose();
  81173. this._skybox = null;
  81174. }
  81175. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81176. this._skyboxMaterial.dispose();
  81177. this._skyboxMaterial = null;
  81178. }
  81179. if (this._skyboxTexture) {
  81180. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81181. this._skyboxTexture.dispose();
  81182. this._skyboxTexture = null;
  81183. }
  81184. }
  81185. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81186. this._groundMirror.dispose();
  81187. this._groundMirror = null;
  81188. }
  81189. if (this._scene.environmentTexture) {
  81190. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81191. this._scene.environmentTexture.dispose();
  81192. }
  81193. }
  81194. this._options = newOptions;
  81195. this._setupBackground();
  81196. this._setupImageProcessing();
  81197. };
  81198. /**
  81199. * Sets the primary color of all the available elements.
  81200. * @param color
  81201. */
  81202. EnvironmentHelper.prototype.setMainColor = function (color) {
  81203. if (this.groundMaterial) {
  81204. this.groundMaterial.primaryColor = color;
  81205. }
  81206. if (this.skyboxMaterial) {
  81207. this.skyboxMaterial.primaryColor = color;
  81208. }
  81209. if (this.groundMirror) {
  81210. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81211. }
  81212. };
  81213. /**
  81214. * Setup the image processing according to the specified options.
  81215. */
  81216. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81217. if (this._options.setupImageProcessing) {
  81218. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81219. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81220. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81221. this._setupEnvironmentTexture();
  81222. }
  81223. };
  81224. /**
  81225. * Setup the environment texture according to the specified options.
  81226. */
  81227. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81228. if (this._scene.environmentTexture) {
  81229. return;
  81230. }
  81231. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81232. this._scene.environmentTexture = this._options.environmentTexture;
  81233. return;
  81234. }
  81235. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81236. this._scene.environmentTexture = environmentTexture;
  81237. };
  81238. /**
  81239. * Setup the background according to the specified options.
  81240. */
  81241. EnvironmentHelper.prototype._setupBackground = function () {
  81242. if (!this._rootMesh) {
  81243. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81244. }
  81245. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81246. var sceneSize = this._getSceneSize();
  81247. if (this._options.createGround) {
  81248. this._setupGround(sceneSize);
  81249. this._setupGroundMaterial();
  81250. this._setupGroundDiffuseTexture();
  81251. if (this._options.enableGroundMirror) {
  81252. this._setupGroundMirrorTexture(sceneSize);
  81253. }
  81254. this._setupMirrorInGroundMaterial();
  81255. }
  81256. if (this._options.createSkybox) {
  81257. this._setupSkybox(sceneSize);
  81258. this._setupSkyboxMaterial();
  81259. this._setupSkyboxReflectionTexture();
  81260. }
  81261. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81262. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81263. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81264. };
  81265. /**
  81266. * Get the scene sizes according to the setup.
  81267. */
  81268. EnvironmentHelper.prototype._getSceneSize = function () {
  81269. var groundSize = this._options.groundSize;
  81270. var skyboxSize = this._options.skyboxSize;
  81271. var rootPosition = this._options.rootPosition;
  81272. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81273. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81274. }
  81275. var sceneExtends = this._scene.getWorldExtends();
  81276. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81277. if (this._options.sizeAuto) {
  81278. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81279. this._scene.activeCamera.upperRadiusLimit) {
  81280. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81281. skyboxSize = groundSize;
  81282. }
  81283. var sceneDiagonalLenght = sceneDiagonal.length();
  81284. if (sceneDiagonalLenght > groundSize) {
  81285. groundSize = sceneDiagonalLenght * 2;
  81286. skyboxSize = groundSize;
  81287. }
  81288. // 10 % bigger.
  81289. groundSize *= 1.1;
  81290. skyboxSize *= 1.5;
  81291. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81292. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81293. }
  81294. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81295. };
  81296. /**
  81297. * Setup the ground according to the specified options.
  81298. */
  81299. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81300. var _this = this;
  81301. if (!this._ground) {
  81302. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81303. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81304. this._ground.parent = this._rootMesh;
  81305. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81306. }
  81307. this._ground.receiveShadows = this._options.enableGroundShadow;
  81308. };
  81309. /**
  81310. * Setup the ground material according to the specified options.
  81311. */
  81312. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81313. if (!this._groundMaterial) {
  81314. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81315. }
  81316. this._groundMaterial.alpha = this._options.groundOpacity;
  81317. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81318. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81319. this._groundMaterial.primaryLevel = 1;
  81320. this._groundMaterial.primaryColor = this._options.groundColor;
  81321. this._groundMaterial.secondaryLevel = 0;
  81322. this._groundMaterial.tertiaryLevel = 0;
  81323. this._groundMaterial.useRGBColor = false;
  81324. this._groundMaterial.enableNoise = true;
  81325. if (this._ground) {
  81326. this._ground.material = this._groundMaterial;
  81327. }
  81328. };
  81329. /**
  81330. * Setup the ground diffuse texture according to the specified options.
  81331. */
  81332. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81333. if (!this._groundMaterial) {
  81334. return;
  81335. }
  81336. if (this._groundTexture) {
  81337. return;
  81338. }
  81339. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81340. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81341. return;
  81342. }
  81343. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81344. diffuseTexture.gammaSpace = false;
  81345. diffuseTexture.hasAlpha = true;
  81346. this._groundMaterial.diffuseTexture = diffuseTexture;
  81347. };
  81348. /**
  81349. * Setup the ground mirror texture according to the specified options.
  81350. */
  81351. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81352. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81353. if (!this._groundMirror) {
  81354. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81355. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81356. this._groundMirror.anisotropicFilteringLevel = 1;
  81357. this._groundMirror.wrapU = wrapping;
  81358. this._groundMirror.wrapV = wrapping;
  81359. this._groundMirror.gammaSpace = false;
  81360. if (this._groundMirror.renderList) {
  81361. for (var i = 0; i < this._scene.meshes.length; i++) {
  81362. var mesh = this._scene.meshes[i];
  81363. if (mesh !== this._ground &&
  81364. mesh !== this._skybox &&
  81365. mesh !== this._rootMesh) {
  81366. this._groundMirror.renderList.push(mesh);
  81367. }
  81368. }
  81369. }
  81370. }
  81371. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81372. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81373. };
  81374. /**
  81375. * Setup the ground to receive the mirror texture.
  81376. */
  81377. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81378. if (this._groundMaterial) {
  81379. this._groundMaterial.reflectionTexture = this._groundMirror;
  81380. this._groundMaterial.reflectionFresnel = true;
  81381. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81382. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81383. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81384. }
  81385. };
  81386. /**
  81387. * Setup the skybox according to the specified options.
  81388. */
  81389. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81390. var _this = this;
  81391. if (!this._skybox) {
  81392. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81393. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81394. }
  81395. this._skybox.parent = this._rootMesh;
  81396. };
  81397. /**
  81398. * Setup the skybox material according to the specified options.
  81399. */
  81400. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81401. if (!this._skybox) {
  81402. return;
  81403. }
  81404. if (!this._skyboxMaterial) {
  81405. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81406. }
  81407. this._skyboxMaterial.useRGBColor = false;
  81408. this._skyboxMaterial.primaryLevel = 1;
  81409. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81410. this._skyboxMaterial.secondaryLevel = 0;
  81411. this._skyboxMaterial.tertiaryLevel = 0;
  81412. this._skyboxMaterial.enableNoise = true;
  81413. this._skybox.material = this._skyboxMaterial;
  81414. };
  81415. /**
  81416. * Setup the skybox reflection texture according to the specified options.
  81417. */
  81418. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81419. if (!this._skyboxMaterial) {
  81420. return;
  81421. }
  81422. if (this._skyboxTexture) {
  81423. return;
  81424. }
  81425. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81426. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81427. return;
  81428. }
  81429. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81430. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81431. this._skyboxTexture.gammaSpace = false;
  81432. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81433. };
  81434. /**
  81435. * Dispose all the elements created by the Helper.
  81436. */
  81437. EnvironmentHelper.prototype.dispose = function () {
  81438. if (this._groundMaterial) {
  81439. this._groundMaterial.dispose(true, true);
  81440. }
  81441. if (this._skyboxMaterial) {
  81442. this._skyboxMaterial.dispose(true, true);
  81443. }
  81444. this._rootMesh.dispose(false);
  81445. };
  81446. /**
  81447. * Default ground texture URL.
  81448. */
  81449. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81450. /**
  81451. * Default skybox texture URL.
  81452. */
  81453. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81454. /**
  81455. * Default environment texture URL.
  81456. */
  81457. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81458. return EnvironmentHelper;
  81459. }());
  81460. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81461. })(BABYLON || (BABYLON = {}));
  81462. //# sourceMappingURL=babylon.environmentHelper.js.map
  81463. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  81464. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  81465. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81466. var BABYLON;
  81467. (function (BABYLON) {
  81468. var GridMaterialDefines = /** @class */ (function (_super) {
  81469. __extends(GridMaterialDefines, _super);
  81470. function GridMaterialDefines() {
  81471. var _this = _super.call(this) || this;
  81472. _this.TRANSPARENT = false;
  81473. _this.FOG = false;
  81474. _this.PREMULTIPLYALPHA = false;
  81475. _this.rebuild();
  81476. return _this;
  81477. }
  81478. return GridMaterialDefines;
  81479. }(BABYLON.MaterialDefines));
  81480. /**
  81481. * The grid materials allows you to wrap any shape with a grid.
  81482. * Colors are customizable.
  81483. */
  81484. var GridMaterial = /** @class */ (function (_super) {
  81485. __extends(GridMaterial, _super);
  81486. /**
  81487. * constructor
  81488. * @param name The name given to the material in order to identify it afterwards.
  81489. * @param scene The scene the material is used in.
  81490. */
  81491. function GridMaterial(name, scene) {
  81492. var _this = _super.call(this, name, scene) || this;
  81493. /**
  81494. * Main color of the grid (e.g. between lines)
  81495. */
  81496. _this.mainColor = BABYLON.Color3.Black();
  81497. /**
  81498. * Color of the grid lines.
  81499. */
  81500. _this.lineColor = BABYLON.Color3.Teal();
  81501. /**
  81502. * The scale of the grid compared to unit.
  81503. */
  81504. _this.gridRatio = 1.0;
  81505. /**
  81506. * Allows setting an offset for the grid lines.
  81507. */
  81508. _this.gridOffset = BABYLON.Vector3.Zero();
  81509. /**
  81510. * The frequency of thicker lines.
  81511. */
  81512. _this.majorUnitFrequency = 10;
  81513. /**
  81514. * The visibility of minor units in the grid.
  81515. */
  81516. _this.minorUnitVisibility = 0.33;
  81517. /**
  81518. * The grid opacity outside of the lines.
  81519. */
  81520. _this.opacity = 1.0;
  81521. /**
  81522. * Determine RBG output is premultiplied by alpha value.
  81523. */
  81524. _this.preMultiplyAlpha = false;
  81525. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  81526. return _this;
  81527. }
  81528. /**
  81529. * Returns wehter or not the grid requires alpha blending.
  81530. */
  81531. GridMaterial.prototype.needAlphaBlending = function () {
  81532. return this.opacity < 1.0;
  81533. };
  81534. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  81535. return this.needAlphaBlending();
  81536. };
  81537. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81538. if (this.isFrozen) {
  81539. if (this._wasPreviouslyReady && subMesh.effect) {
  81540. return true;
  81541. }
  81542. }
  81543. if (!subMesh._materialDefines) {
  81544. subMesh._materialDefines = new GridMaterialDefines();
  81545. }
  81546. var defines = subMesh._materialDefines;
  81547. var scene = this.getScene();
  81548. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81549. if (this._renderId === scene.getRenderId()) {
  81550. return true;
  81551. }
  81552. }
  81553. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  81554. defines.TRANSPARENT = !defines.TRANSPARENT;
  81555. defines.markAsUnprocessed();
  81556. }
  81557. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  81558. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  81559. defines.markAsUnprocessed();
  81560. }
  81561. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  81562. // Get correct effect
  81563. if (defines.isDirty) {
  81564. defines.markAsProcessed();
  81565. scene.resetCachedMaterial();
  81566. // Attributes
  81567. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81568. // Defines
  81569. var join = defines.toString();
  81570. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  81571. }
  81572. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81573. return false;
  81574. }
  81575. this._renderId = scene.getRenderId();
  81576. this._wasPreviouslyReady = true;
  81577. return true;
  81578. };
  81579. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81580. var scene = this.getScene();
  81581. var defines = subMesh._materialDefines;
  81582. if (!defines) {
  81583. return;
  81584. }
  81585. var effect = subMesh.effect;
  81586. if (!effect) {
  81587. return;
  81588. }
  81589. this._activeEffect = effect;
  81590. // Matrices
  81591. this.bindOnlyWorldMatrix(world);
  81592. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  81593. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  81594. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  81595. // Uniforms
  81596. if (this._mustRebind(scene, effect)) {
  81597. this._activeEffect.setColor3("mainColor", this.mainColor);
  81598. this._activeEffect.setColor3("lineColor", this.lineColor);
  81599. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  81600. this._gridControl.x = this.gridRatio;
  81601. this._gridControl.y = Math.round(this.majorUnitFrequency);
  81602. this._gridControl.z = this.minorUnitVisibility;
  81603. this._gridControl.w = this.opacity;
  81604. this._activeEffect.setVector4("gridControl", this._gridControl);
  81605. }
  81606. // Fog
  81607. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81608. this._afterBind(mesh, this._activeEffect);
  81609. };
  81610. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  81611. _super.prototype.dispose.call(this, forceDisposeEffect);
  81612. };
  81613. GridMaterial.prototype.clone = function (name) {
  81614. var _this = this;
  81615. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  81616. };
  81617. GridMaterial.prototype.serialize = function () {
  81618. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81619. serializationObject.customType = "BABYLON.GridMaterial";
  81620. return serializationObject;
  81621. };
  81622. GridMaterial.prototype.getClassName = function () {
  81623. return "GridMaterial";
  81624. };
  81625. GridMaterial.Parse = function (source, scene, rootUrl) {
  81626. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  81627. };
  81628. __decorate([
  81629. BABYLON.serializeAsColor3()
  81630. ], GridMaterial.prototype, "mainColor", void 0);
  81631. __decorate([
  81632. BABYLON.serializeAsColor3()
  81633. ], GridMaterial.prototype, "lineColor", void 0);
  81634. __decorate([
  81635. BABYLON.serialize()
  81636. ], GridMaterial.prototype, "gridRatio", void 0);
  81637. __decorate([
  81638. BABYLON.serializeAsColor3()
  81639. ], GridMaterial.prototype, "gridOffset", void 0);
  81640. __decorate([
  81641. BABYLON.serialize()
  81642. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  81643. __decorate([
  81644. BABYLON.serialize()
  81645. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  81646. __decorate([
  81647. BABYLON.serialize()
  81648. ], GridMaterial.prototype, "opacity", void 0);
  81649. __decorate([
  81650. BABYLON.serialize()
  81651. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  81652. return GridMaterial;
  81653. }(BABYLON.PushMaterial));
  81654. BABYLON.GridMaterial = GridMaterial;
  81655. })(BABYLON || (BABYLON = {}));
  81656. //# sourceMappingURL=babylon.gridmaterial.js.map
  81657. 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}";
  81658. 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}";
  81659. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81660. var BABYLON;
  81661. (function (BABYLON) {
  81662. var GLTFLoaderCoordinateSystemMode;
  81663. (function (GLTFLoaderCoordinateSystemMode) {
  81664. /**
  81665. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  81666. */
  81667. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  81668. /**
  81669. * Sets the useRightHandedSystem flag on the scene.
  81670. */
  81671. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  81672. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  81673. var GLTFLoaderAnimationStartMode;
  81674. (function (GLTFLoaderAnimationStartMode) {
  81675. /**
  81676. * No animation will start.
  81677. */
  81678. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  81679. /**
  81680. * The first animation will start.
  81681. */
  81682. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  81683. /**
  81684. * All animations will start.
  81685. */
  81686. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  81687. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  81688. var GLTFFileLoader = /** @class */ (function () {
  81689. function GLTFFileLoader() {
  81690. // #region Common options
  81691. /**
  81692. * Raised when the asset has been parsed.
  81693. * The data.json property stores the glTF JSON.
  81694. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  81695. */
  81696. this.onParsedObservable = new BABYLON.Observable();
  81697. // #endregion
  81698. // #region V2 options
  81699. /**
  81700. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  81701. */
  81702. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  81703. /**
  81704. * The animation start mode (NONE, FIRST, ALL).
  81705. */
  81706. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  81707. /**
  81708. * Set to true to compile materials before raising the success callback.
  81709. */
  81710. this.compileMaterials = false;
  81711. /**
  81712. * Set to true to also compile materials with clip planes.
  81713. */
  81714. this.useClipPlane = false;
  81715. /**
  81716. * Set to true to compile shadow generators before raising the success callback.
  81717. */
  81718. this.compileShadowGenerators = false;
  81719. /**
  81720. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  81721. */
  81722. this.onMeshLoadedObservable = new BABYLON.Observable();
  81723. /**
  81724. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  81725. */
  81726. this.onTextureLoadedObservable = new BABYLON.Observable();
  81727. /**
  81728. * Raised when the loader creates a material after parsing the glTF properties of the material.
  81729. */
  81730. this.onMaterialLoadedObservable = new BABYLON.Observable();
  81731. /**
  81732. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81733. * For assets with LODs, raised when all of the LODs are complete.
  81734. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  81735. */
  81736. this.onCompleteObservable = new BABYLON.Observable();
  81737. /**
  81738. * Raised when the loader is disposed.
  81739. */
  81740. this.onDisposeObservable = new BABYLON.Observable();
  81741. // #endregion
  81742. this._loader = null;
  81743. this.name = "gltf";
  81744. this.extensions = {
  81745. ".gltf": { isBinary: false },
  81746. ".glb": { isBinary: true }
  81747. };
  81748. }
  81749. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  81750. set: function (callback) {
  81751. if (this._onParsedObserver) {
  81752. this.onParsedObservable.remove(this._onParsedObserver);
  81753. }
  81754. this._onParsedObserver = this.onParsedObservable.add(callback);
  81755. },
  81756. enumerable: true,
  81757. configurable: true
  81758. });
  81759. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  81760. set: function (callback) {
  81761. if (this._onMeshLoadedObserver) {
  81762. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  81763. }
  81764. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  81765. },
  81766. enumerable: true,
  81767. configurable: true
  81768. });
  81769. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  81770. set: function (callback) {
  81771. if (this._onTextureLoadedObserver) {
  81772. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  81773. }
  81774. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  81775. },
  81776. enumerable: true,
  81777. configurable: true
  81778. });
  81779. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  81780. set: function (callback) {
  81781. if (this._onMaterialLoadedObserver) {
  81782. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  81783. }
  81784. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  81785. },
  81786. enumerable: true,
  81787. configurable: true
  81788. });
  81789. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  81790. set: function (callback) {
  81791. if (this._onCompleteObserver) {
  81792. this.onCompleteObservable.remove(this._onCompleteObserver);
  81793. }
  81794. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  81795. },
  81796. enumerable: true,
  81797. configurable: true
  81798. });
  81799. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  81800. set: function (callback) {
  81801. if (this._onDisposeObserver) {
  81802. this.onDisposeObservable.remove(this._onDisposeObserver);
  81803. }
  81804. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81805. },
  81806. enumerable: true,
  81807. configurable: true
  81808. });
  81809. /**
  81810. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  81811. */
  81812. GLTFFileLoader.prototype.dispose = function () {
  81813. if (this._loader) {
  81814. this._loader.dispose();
  81815. this._loader = null;
  81816. }
  81817. this.onParsedObservable.clear();
  81818. this.onMeshLoadedObservable.clear();
  81819. this.onTextureLoadedObservable.clear();
  81820. this.onMaterialLoadedObservable.clear();
  81821. this.onCompleteObservable.clear();
  81822. this.onDisposeObservable.notifyObservers(this);
  81823. this.onDisposeObservable.clear();
  81824. };
  81825. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81826. try {
  81827. var loaderData = this._parse(data);
  81828. this._loader = this._getLoader(loaderData);
  81829. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  81830. }
  81831. catch (e) {
  81832. if (onError) {
  81833. onError(e.message, e);
  81834. }
  81835. else {
  81836. BABYLON.Tools.Error(e.message);
  81837. }
  81838. }
  81839. };
  81840. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81841. try {
  81842. var loaderData = this._parse(data);
  81843. this._loader = this._getLoader(loaderData);
  81844. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  81845. }
  81846. catch (e) {
  81847. if (onError) {
  81848. onError(e.message, e);
  81849. }
  81850. else {
  81851. BABYLON.Tools.Error(e.message);
  81852. }
  81853. }
  81854. };
  81855. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81856. try {
  81857. var loaderData = this._parse(data);
  81858. this._loader = this._getLoader(loaderData);
  81859. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  81860. var container = new BABYLON.AssetContainer(scene);
  81861. Array.prototype.push.apply(container.meshes, meshes);
  81862. Array.prototype.push.apply(container.particleSystems, particleSystems);
  81863. Array.prototype.push.apply(container.skeletons, skeletons);
  81864. container.removeAllFromScene();
  81865. onSuccess(container);
  81866. }, onProgress, onError);
  81867. }
  81868. catch (e) {
  81869. if (onError) {
  81870. onError(e.message, e);
  81871. }
  81872. else {
  81873. BABYLON.Tools.Error(e.message);
  81874. }
  81875. }
  81876. };
  81877. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  81878. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  81879. };
  81880. GLTFFileLoader.prototype.createPlugin = function () {
  81881. return new GLTFFileLoader();
  81882. };
  81883. GLTFFileLoader.prototype._parse = function (data) {
  81884. var parsedData;
  81885. if (data instanceof ArrayBuffer) {
  81886. parsedData = GLTFFileLoader._parseBinary(data);
  81887. }
  81888. else {
  81889. parsedData = {
  81890. json: JSON.parse(data),
  81891. bin: null
  81892. };
  81893. }
  81894. this.onParsedObservable.notifyObservers(parsedData);
  81895. return parsedData;
  81896. };
  81897. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  81898. var _this = this;
  81899. var loaderVersion = { major: 2, minor: 0 };
  81900. var asset = loaderData.json.asset || {};
  81901. var version = GLTFFileLoader._parseVersion(asset.version);
  81902. if (!version) {
  81903. throw new Error("Invalid version: " + asset.version);
  81904. }
  81905. if (asset.minVersion !== undefined) {
  81906. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  81907. if (!minVersion) {
  81908. throw new Error("Invalid minimum version: " + asset.minVersion);
  81909. }
  81910. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  81911. throw new Error("Incompatible minimum version: " + asset.minVersion);
  81912. }
  81913. }
  81914. var createLoaders = {
  81915. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  81916. 2: GLTFFileLoader.CreateGLTFLoaderV2
  81917. };
  81918. var createLoader = createLoaders[version.major];
  81919. if (!createLoader) {
  81920. throw new Error("Unsupported version: " + asset.version);
  81921. }
  81922. var loader = createLoader();
  81923. loader.coordinateSystemMode = this.coordinateSystemMode;
  81924. loader.animationStartMode = this.animationStartMode;
  81925. loader.compileMaterials = this.compileMaterials;
  81926. loader.useClipPlane = this.useClipPlane;
  81927. loader.compileShadowGenerators = this.compileShadowGenerators;
  81928. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  81929. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  81930. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  81931. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  81932. return loader;
  81933. };
  81934. GLTFFileLoader._parseBinary = function (data) {
  81935. var Binary = {
  81936. Magic: 0x46546C67
  81937. };
  81938. var binaryReader = new BinaryReader(data);
  81939. var magic = binaryReader.readUint32();
  81940. if (magic !== Binary.Magic) {
  81941. throw new Error("Unexpected magic: " + magic);
  81942. }
  81943. var version = binaryReader.readUint32();
  81944. switch (version) {
  81945. case 1: return GLTFFileLoader._parseV1(binaryReader);
  81946. case 2: return GLTFFileLoader._parseV2(binaryReader);
  81947. }
  81948. throw new Error("Unsupported version: " + version);
  81949. };
  81950. GLTFFileLoader._parseV1 = function (binaryReader) {
  81951. var ContentFormat = {
  81952. JSON: 0
  81953. };
  81954. var length = binaryReader.readUint32();
  81955. if (length != binaryReader.getLength()) {
  81956. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  81957. }
  81958. var contentLength = binaryReader.readUint32();
  81959. var contentFormat = binaryReader.readUint32();
  81960. var content;
  81961. switch (contentFormat) {
  81962. case ContentFormat.JSON: {
  81963. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  81964. break;
  81965. }
  81966. default: {
  81967. throw new Error("Unexpected content format: " + contentFormat);
  81968. }
  81969. }
  81970. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  81971. var body = binaryReader.readUint8Array(bytesRemaining);
  81972. return {
  81973. json: content,
  81974. bin: body
  81975. };
  81976. };
  81977. GLTFFileLoader._parseV2 = function (binaryReader) {
  81978. var ChunkFormat = {
  81979. JSON: 0x4E4F534A,
  81980. BIN: 0x004E4942
  81981. };
  81982. var length = binaryReader.readUint32();
  81983. if (length !== binaryReader.getLength()) {
  81984. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  81985. }
  81986. // JSON chunk
  81987. var chunkLength = binaryReader.readUint32();
  81988. var chunkFormat = binaryReader.readUint32();
  81989. if (chunkFormat !== ChunkFormat.JSON) {
  81990. throw new Error("First chunk format is not JSON");
  81991. }
  81992. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  81993. // Look for BIN chunk
  81994. var bin = null;
  81995. while (binaryReader.getPosition() < binaryReader.getLength()) {
  81996. var chunkLength_1 = binaryReader.readUint32();
  81997. var chunkFormat_1 = binaryReader.readUint32();
  81998. switch (chunkFormat_1) {
  81999. case ChunkFormat.JSON: {
  82000. throw new Error("Unexpected JSON chunk");
  82001. }
  82002. case ChunkFormat.BIN: {
  82003. bin = binaryReader.readUint8Array(chunkLength_1);
  82004. break;
  82005. }
  82006. default: {
  82007. // ignore unrecognized chunkFormat
  82008. binaryReader.skipBytes(chunkLength_1);
  82009. break;
  82010. }
  82011. }
  82012. }
  82013. return {
  82014. json: json,
  82015. bin: bin
  82016. };
  82017. };
  82018. GLTFFileLoader._parseVersion = function (version) {
  82019. if (version === "1.0" || version === "1.0.1") {
  82020. return {
  82021. major: 1,
  82022. minor: 0
  82023. };
  82024. }
  82025. var match = (version + "").match(/^(\d+)\.(\d+)/);
  82026. if (!match) {
  82027. return null;
  82028. }
  82029. return {
  82030. major: parseInt(match[1]),
  82031. minor: parseInt(match[2])
  82032. };
  82033. };
  82034. GLTFFileLoader._compareVersion = function (a, b) {
  82035. if (a.major > b.major)
  82036. return 1;
  82037. if (a.major < b.major)
  82038. return -1;
  82039. if (a.minor > b.minor)
  82040. return 1;
  82041. if (a.minor < b.minor)
  82042. return -1;
  82043. return 0;
  82044. };
  82045. GLTFFileLoader._decodeBufferToText = function (buffer) {
  82046. var result = "";
  82047. var length = buffer.byteLength;
  82048. for (var i = 0; i < length; i++) {
  82049. result += String.fromCharCode(buffer[i]);
  82050. }
  82051. return result;
  82052. };
  82053. // #endregion
  82054. // #region V1 options
  82055. GLTFFileLoader.IncrementalLoading = true;
  82056. GLTFFileLoader.HomogeneousCoordinates = false;
  82057. return GLTFFileLoader;
  82058. }());
  82059. BABYLON.GLTFFileLoader = GLTFFileLoader;
  82060. var BinaryReader = /** @class */ (function () {
  82061. function BinaryReader(arrayBuffer) {
  82062. this._arrayBuffer = arrayBuffer;
  82063. this._dataView = new DataView(arrayBuffer);
  82064. this._byteOffset = 0;
  82065. }
  82066. BinaryReader.prototype.getPosition = function () {
  82067. return this._byteOffset;
  82068. };
  82069. BinaryReader.prototype.getLength = function () {
  82070. return this._arrayBuffer.byteLength;
  82071. };
  82072. BinaryReader.prototype.readUint32 = function () {
  82073. var value = this._dataView.getUint32(this._byteOffset, true);
  82074. this._byteOffset += 4;
  82075. return value;
  82076. };
  82077. BinaryReader.prototype.readUint8Array = function (length) {
  82078. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  82079. this._byteOffset += length;
  82080. return value;
  82081. };
  82082. BinaryReader.prototype.skipBytes = function (length) {
  82083. this._byteOffset += length;
  82084. };
  82085. return BinaryReader;
  82086. }());
  82087. if (BABYLON.SceneLoader) {
  82088. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  82089. }
  82090. })(BABYLON || (BABYLON = {}));
  82091. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  82092. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82093. var BABYLON;
  82094. (function (BABYLON) {
  82095. var GLTF1;
  82096. (function (GLTF1) {
  82097. /**
  82098. * Enums
  82099. */
  82100. var EComponentType;
  82101. (function (EComponentType) {
  82102. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82103. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82104. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82105. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82106. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82107. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  82108. var EShaderType;
  82109. (function (EShaderType) {
  82110. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  82111. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  82112. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  82113. var EParameterType;
  82114. (function (EParameterType) {
  82115. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  82116. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82117. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  82118. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82119. EParameterType[EParameterType["INT"] = 5124] = "INT";
  82120. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82121. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  82122. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  82123. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  82124. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  82125. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  82126. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  82127. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  82128. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  82129. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  82130. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  82131. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  82132. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  82133. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  82134. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  82135. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  82136. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  82137. var ETextureWrapMode;
  82138. (function (ETextureWrapMode) {
  82139. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82140. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82141. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82142. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  82143. var ETextureFilterType;
  82144. (function (ETextureFilterType) {
  82145. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  82146. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  82147. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82148. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82149. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82150. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82151. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  82152. var ETextureFormat;
  82153. (function (ETextureFormat) {
  82154. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  82155. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  82156. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  82157. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  82158. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  82159. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  82160. var ECullingType;
  82161. (function (ECullingType) {
  82162. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  82163. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  82164. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  82165. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  82166. var EBlendingFunction;
  82167. (function (EBlendingFunction) {
  82168. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  82169. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  82170. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  82171. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  82172. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  82173. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  82174. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82175. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  82176. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  82177. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  82178. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  82179. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  82180. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  82181. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  82182. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  82183. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  82184. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82185. })(BABYLON || (BABYLON = {}));
  82186. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82187. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82188. var BABYLON;
  82189. (function (BABYLON) {
  82190. var GLTF1;
  82191. (function (GLTF1) {
  82192. /**
  82193. * Tokenizer. Used for shaders compatibility
  82194. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  82195. */
  82196. var ETokenType;
  82197. (function (ETokenType) {
  82198. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  82199. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  82200. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  82201. })(ETokenType || (ETokenType = {}));
  82202. var Tokenizer = /** @class */ (function () {
  82203. function Tokenizer(toParse) {
  82204. this._pos = 0;
  82205. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  82206. this._toParse = toParse;
  82207. this._maxPos = toParse.length;
  82208. }
  82209. Tokenizer.prototype.getNextToken = function () {
  82210. if (this.isEnd())
  82211. return ETokenType.END_OF_INPUT;
  82212. this.currentString = this.read();
  82213. this.currentToken = ETokenType.UNKNOWN;
  82214. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  82215. this.currentToken = ETokenType.IDENTIFIER;
  82216. this.currentIdentifier = this.currentString;
  82217. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  82218. this.currentIdentifier += this.currentString;
  82219. this.forward();
  82220. }
  82221. }
  82222. return this.currentToken;
  82223. };
  82224. Tokenizer.prototype.peek = function () {
  82225. return this._toParse[this._pos];
  82226. };
  82227. Tokenizer.prototype.read = function () {
  82228. return this._toParse[this._pos++];
  82229. };
  82230. Tokenizer.prototype.forward = function () {
  82231. this._pos++;
  82232. };
  82233. Tokenizer.prototype.isEnd = function () {
  82234. return this._pos >= this._maxPos;
  82235. };
  82236. return Tokenizer;
  82237. }());
  82238. /**
  82239. * Values
  82240. */
  82241. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  82242. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  82243. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  82244. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  82245. /**
  82246. * Parse
  82247. */
  82248. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  82249. for (var buf in parsedBuffers) {
  82250. var parsedBuffer = parsedBuffers[buf];
  82251. gltfRuntime.buffers[buf] = parsedBuffer;
  82252. gltfRuntime.buffersCount++;
  82253. }
  82254. };
  82255. var parseShaders = function (parsedShaders, gltfRuntime) {
  82256. for (var sha in parsedShaders) {
  82257. var parsedShader = parsedShaders[sha];
  82258. gltfRuntime.shaders[sha] = parsedShader;
  82259. gltfRuntime.shaderscount++;
  82260. }
  82261. };
  82262. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  82263. for (var object in parsedObjects) {
  82264. var parsedObject = parsedObjects[object];
  82265. gltfRuntime[runtimeProperty][object] = parsedObject;
  82266. }
  82267. };
  82268. /**
  82269. * Utils
  82270. */
  82271. var normalizeUVs = function (buffer) {
  82272. if (!buffer) {
  82273. return;
  82274. }
  82275. for (var i = 0; i < buffer.length / 2; i++) {
  82276. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  82277. }
  82278. };
  82279. var getAttribute = function (attributeParameter) {
  82280. if (attributeParameter.semantic === "NORMAL") {
  82281. return "normal";
  82282. }
  82283. else if (attributeParameter.semantic === "POSITION") {
  82284. return "position";
  82285. }
  82286. else if (attributeParameter.semantic === "JOINT") {
  82287. return "matricesIndices";
  82288. }
  82289. else if (attributeParameter.semantic === "WEIGHT") {
  82290. return "matricesWeights";
  82291. }
  82292. else if (attributeParameter.semantic === "COLOR") {
  82293. return "color";
  82294. }
  82295. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  82296. var channel = Number(attributeParameter.semantic.split("_")[1]);
  82297. return "uv" + (channel === 0 ? "" : channel + 1);
  82298. }
  82299. return null;
  82300. };
  82301. /**
  82302. * Loads and creates animations
  82303. */
  82304. var loadAnimations = function (gltfRuntime) {
  82305. for (var anim in gltfRuntime.animations) {
  82306. var animation = gltfRuntime.animations[anim];
  82307. if (!animation.channels || !animation.samplers) {
  82308. continue;
  82309. }
  82310. var lastAnimation = null;
  82311. for (var i = 0; i < animation.channels.length; i++) {
  82312. // Get parameters and load buffers
  82313. var channel = animation.channels[i];
  82314. var sampler = animation.samplers[channel.sampler];
  82315. if (!sampler) {
  82316. continue;
  82317. }
  82318. var inputData = null;
  82319. var outputData = null;
  82320. if (animation.parameters) {
  82321. inputData = animation.parameters[sampler.input];
  82322. outputData = animation.parameters[sampler.output];
  82323. }
  82324. else {
  82325. inputData = sampler.input;
  82326. outputData = sampler.output;
  82327. }
  82328. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  82329. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  82330. var targetID = channel.target.id;
  82331. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  82332. if (targetNode === null) {
  82333. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  82334. }
  82335. if (targetNode === null) {
  82336. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  82337. continue;
  82338. }
  82339. var isBone = targetNode instanceof BABYLON.Bone;
  82340. // Get target path (position, rotation or scaling)
  82341. var targetPath = channel.target.path;
  82342. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  82343. if (targetPathIndex !== -1) {
  82344. targetPath = babylonAnimationPaths[targetPathIndex];
  82345. }
  82346. // Determine animation type
  82347. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  82348. if (!isBone) {
  82349. if (targetPath === "rotationQuaternion") {
  82350. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82351. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  82352. }
  82353. else {
  82354. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82355. }
  82356. }
  82357. // Create animation and key frames
  82358. var babylonAnimation = null;
  82359. var keys = [];
  82360. var arrayOffset = 0;
  82361. var modifyKey = false;
  82362. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  82363. babylonAnimation = lastAnimation;
  82364. modifyKey = true;
  82365. }
  82366. if (!modifyKey) {
  82367. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82368. }
  82369. // For each frame
  82370. for (var j = 0; j < bufferInput.length; j++) {
  82371. var value = null;
  82372. if (targetPath === "rotationQuaternion") {
  82373. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  82374. arrayOffset += 4;
  82375. }
  82376. else {
  82377. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  82378. arrayOffset += 3;
  82379. }
  82380. if (isBone) {
  82381. var bone = targetNode;
  82382. var translation = BABYLON.Vector3.Zero();
  82383. var rotationQuaternion = new BABYLON.Quaternion();
  82384. var scaling = BABYLON.Vector3.Zero();
  82385. // Warning on decompose
  82386. var mat = bone.getBaseMatrix();
  82387. if (modifyKey && lastAnimation) {
  82388. mat = lastAnimation.getKeys()[j].value;
  82389. }
  82390. mat.decompose(scaling, rotationQuaternion, translation);
  82391. if (targetPath === "position") {
  82392. translation = value;
  82393. }
  82394. else if (targetPath === "rotationQuaternion") {
  82395. rotationQuaternion = value;
  82396. }
  82397. else {
  82398. scaling = value;
  82399. }
  82400. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  82401. }
  82402. if (!modifyKey) {
  82403. keys.push({
  82404. frame: bufferInput[j],
  82405. value: value
  82406. });
  82407. }
  82408. else if (lastAnimation) {
  82409. lastAnimation.getKeys()[j].value = value;
  82410. }
  82411. }
  82412. // Finish
  82413. if (!modifyKey && babylonAnimation) {
  82414. babylonAnimation.setKeys(keys);
  82415. targetNode.animations.push(babylonAnimation);
  82416. }
  82417. lastAnimation = babylonAnimation;
  82418. gltfRuntime.scene.stopAnimation(targetNode);
  82419. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  82420. }
  82421. }
  82422. };
  82423. /**
  82424. * Returns the bones transformation matrix
  82425. */
  82426. var configureBoneTransformation = function (node) {
  82427. var mat = null;
  82428. if (node.translation || node.rotation || node.scale) {
  82429. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  82430. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  82431. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  82432. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  82433. }
  82434. else {
  82435. mat = BABYLON.Matrix.FromArray(node.matrix);
  82436. }
  82437. return mat;
  82438. };
  82439. /**
  82440. * Returns the parent bone
  82441. */
  82442. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  82443. // Try to find
  82444. for (var i = 0; i < newSkeleton.bones.length; i++) {
  82445. if (newSkeleton.bones[i].name === jointName) {
  82446. return newSkeleton.bones[i];
  82447. }
  82448. }
  82449. // Not found, search in gltf nodes
  82450. var nodes = gltfRuntime.nodes;
  82451. for (var nde in nodes) {
  82452. var node = nodes[nde];
  82453. if (!node.jointName) {
  82454. continue;
  82455. }
  82456. var children = node.children;
  82457. for (var i = 0; i < children.length; i++) {
  82458. var child = gltfRuntime.nodes[children[i]];
  82459. if (!child.jointName) {
  82460. continue;
  82461. }
  82462. if (child.jointName === jointName) {
  82463. var mat = configureBoneTransformation(node);
  82464. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  82465. bone.id = nde;
  82466. return bone;
  82467. }
  82468. }
  82469. }
  82470. return null;
  82471. };
  82472. /**
  82473. * Returns the appropriate root node
  82474. */
  82475. var getNodeToRoot = function (nodesToRoot, id) {
  82476. for (var i = 0; i < nodesToRoot.length; i++) {
  82477. var nodeToRoot = nodesToRoot[i];
  82478. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  82479. var child = nodeToRoot.node.children[j];
  82480. if (child === id) {
  82481. return nodeToRoot.bone;
  82482. }
  82483. }
  82484. }
  82485. return null;
  82486. };
  82487. /**
  82488. * Returns the node with the joint name
  82489. */
  82490. var getJointNode = function (gltfRuntime, jointName) {
  82491. var nodes = gltfRuntime.nodes;
  82492. var node = nodes[jointName];
  82493. if (node) {
  82494. return {
  82495. node: node,
  82496. id: jointName
  82497. };
  82498. }
  82499. for (var nde in nodes) {
  82500. node = nodes[nde];
  82501. if (node.jointName === jointName) {
  82502. return {
  82503. node: node,
  82504. id: nde
  82505. };
  82506. }
  82507. }
  82508. return null;
  82509. };
  82510. /**
  82511. * Checks if a nodes is in joints
  82512. */
  82513. var nodeIsInJoints = function (skins, id) {
  82514. for (var i = 0; i < skins.jointNames.length; i++) {
  82515. if (skins.jointNames[i] === id) {
  82516. return true;
  82517. }
  82518. }
  82519. return false;
  82520. };
  82521. /**
  82522. * Fills the nodes to root for bones and builds hierarchy
  82523. */
  82524. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  82525. // Creates nodes for root
  82526. for (var nde in gltfRuntime.nodes) {
  82527. var node = gltfRuntime.nodes[nde];
  82528. var id = nde;
  82529. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  82530. continue;
  82531. }
  82532. // Create node to root bone
  82533. var mat = configureBoneTransformation(node);
  82534. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  82535. bone.id = id;
  82536. nodesToRoot.push({ bone: bone, node: node, id: id });
  82537. }
  82538. // Parenting
  82539. for (var i = 0; i < nodesToRoot.length; i++) {
  82540. var nodeToRoot = nodesToRoot[i];
  82541. var children = nodeToRoot.node.children;
  82542. for (var j = 0; j < children.length; j++) {
  82543. var child = null;
  82544. for (var k = 0; k < nodesToRoot.length; k++) {
  82545. if (nodesToRoot[k].id === children[j]) {
  82546. child = nodesToRoot[k];
  82547. break;
  82548. }
  82549. }
  82550. if (child) {
  82551. child.bone._parent = nodeToRoot.bone;
  82552. nodeToRoot.bone.children.push(child.bone);
  82553. }
  82554. }
  82555. }
  82556. };
  82557. /**
  82558. * Imports a skeleton
  82559. */
  82560. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  82561. if (!newSkeleton) {
  82562. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  82563. }
  82564. if (!skins.babylonSkeleton) {
  82565. return newSkeleton;
  82566. }
  82567. // Find the root bones
  82568. var nodesToRoot = [];
  82569. var nodesToRootToAdd = [];
  82570. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  82571. newSkeleton.bones = [];
  82572. // Joints
  82573. for (var i = 0; i < skins.jointNames.length; i++) {
  82574. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82575. if (!jointNode) {
  82576. continue;
  82577. }
  82578. var node = jointNode.node;
  82579. if (!node) {
  82580. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  82581. continue;
  82582. }
  82583. var id = jointNode.id;
  82584. // Optimize, if the bone already exists...
  82585. var existingBone = gltfRuntime.scene.getBoneByID(id);
  82586. if (existingBone) {
  82587. newSkeleton.bones.push(existingBone);
  82588. continue;
  82589. }
  82590. // Search for parent bone
  82591. var foundBone = false;
  82592. var parentBone = null;
  82593. for (var j = 0; j < i; j++) {
  82594. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  82595. if (!jointNode_1) {
  82596. continue;
  82597. }
  82598. var joint = jointNode_1.node;
  82599. if (!joint) {
  82600. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  82601. continue;
  82602. }
  82603. var children = joint.children;
  82604. if (!children) {
  82605. continue;
  82606. }
  82607. foundBone = false;
  82608. for (var k = 0; k < children.length; k++) {
  82609. if (children[k] === id) {
  82610. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  82611. foundBone = true;
  82612. break;
  82613. }
  82614. }
  82615. if (foundBone) {
  82616. break;
  82617. }
  82618. }
  82619. // Create bone
  82620. var mat = configureBoneTransformation(node);
  82621. if (!parentBone && nodesToRoot.length > 0) {
  82622. parentBone = getNodeToRoot(nodesToRoot, id);
  82623. if (parentBone) {
  82624. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  82625. nodesToRootToAdd.push(parentBone);
  82626. }
  82627. }
  82628. }
  82629. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  82630. bone.id = id;
  82631. }
  82632. // Polish
  82633. var bones = newSkeleton.bones;
  82634. newSkeleton.bones = [];
  82635. for (var i = 0; i < skins.jointNames.length; i++) {
  82636. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82637. if (!jointNode) {
  82638. continue;
  82639. }
  82640. for (var j = 0; j < bones.length; j++) {
  82641. if (bones[j].id === jointNode.id) {
  82642. newSkeleton.bones.push(bones[j]);
  82643. break;
  82644. }
  82645. }
  82646. }
  82647. newSkeleton.prepare();
  82648. // Finish
  82649. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  82650. newSkeleton.bones.push(nodesToRootToAdd[i]);
  82651. }
  82652. return newSkeleton;
  82653. };
  82654. /**
  82655. * Imports a mesh and its geometries
  82656. */
  82657. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  82658. if (!newMesh) {
  82659. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82660. newMesh.id = id;
  82661. }
  82662. if (!node.babylonNode) {
  82663. return newMesh;
  82664. }
  82665. var subMaterials = [];
  82666. var vertexData = new BABYLON.VertexData();
  82667. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  82668. var verticesStarts = new Array();
  82669. var verticesCounts = new Array();
  82670. var indexStarts = new Array();
  82671. var indexCounts = new Array();
  82672. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82673. var meshID = meshes[meshIndex];
  82674. var mesh = gltfRuntime.meshes[meshID];
  82675. if (!mesh) {
  82676. continue;
  82677. }
  82678. // Positions, normals and UVs
  82679. for (var i = 0; i < mesh.primitives.length; i++) {
  82680. // Temporary vertex data
  82681. var tempVertexData = new BABYLON.VertexData();
  82682. var primitive = mesh.primitives[i];
  82683. if (primitive.mode !== 4) {
  82684. // continue;
  82685. }
  82686. var attributes = primitive.attributes;
  82687. var accessor = null;
  82688. var buffer = null;
  82689. // Set positions, normal and uvs
  82690. for (var semantic in attributes) {
  82691. // Link accessor and buffer view
  82692. accessor = gltfRuntime.accessors[attributes[semantic]];
  82693. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82694. if (semantic === "NORMAL") {
  82695. tempVertexData.normals = new Float32Array(buffer.length);
  82696. tempVertexData.normals.set(buffer);
  82697. }
  82698. else if (semantic === "POSITION") {
  82699. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  82700. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  82701. for (var j = 0; j < buffer.length; j += 4) {
  82702. tempVertexData.positions[j] = buffer[j];
  82703. tempVertexData.positions[j + 1] = buffer[j + 1];
  82704. tempVertexData.positions[j + 2] = buffer[j + 2];
  82705. }
  82706. }
  82707. else {
  82708. tempVertexData.positions = new Float32Array(buffer.length);
  82709. tempVertexData.positions.set(buffer);
  82710. }
  82711. verticesCounts.push(tempVertexData.positions.length);
  82712. }
  82713. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  82714. var channel = Number(semantic.split("_")[1]);
  82715. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  82716. var uvs = new Float32Array(buffer.length);
  82717. uvs.set(buffer);
  82718. normalizeUVs(uvs);
  82719. tempVertexData.set(uvs, uvKind);
  82720. }
  82721. else if (semantic === "JOINT") {
  82722. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  82723. tempVertexData.matricesIndices.set(buffer);
  82724. }
  82725. else if (semantic === "WEIGHT") {
  82726. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  82727. tempVertexData.matricesWeights.set(buffer);
  82728. }
  82729. else if (semantic === "COLOR") {
  82730. tempVertexData.colors = new Float32Array(buffer.length);
  82731. tempVertexData.colors.set(buffer);
  82732. }
  82733. }
  82734. // Indices
  82735. accessor = gltfRuntime.accessors[primitive.indices];
  82736. if (accessor) {
  82737. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82738. tempVertexData.indices = new Int32Array(buffer.length);
  82739. tempVertexData.indices.set(buffer);
  82740. indexCounts.push(tempVertexData.indices.length);
  82741. }
  82742. else {
  82743. // Set indices on the fly
  82744. var indices = [];
  82745. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  82746. indices.push(j);
  82747. }
  82748. tempVertexData.indices = new Int32Array(indices);
  82749. indexCounts.push(tempVertexData.indices.length);
  82750. }
  82751. vertexData.merge(tempVertexData);
  82752. // Sub material
  82753. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  82754. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  82755. // Update vertices start and index start
  82756. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  82757. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  82758. }
  82759. }
  82760. var material;
  82761. if (subMaterials.length > 1) {
  82762. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  82763. material.subMaterials = subMaterials;
  82764. }
  82765. else {
  82766. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  82767. }
  82768. if (subMaterials.length === 1) {
  82769. material = subMaterials[0];
  82770. }
  82771. if (!newMesh.material) {
  82772. newMesh.material = material;
  82773. }
  82774. // Apply geometry
  82775. geometry.setAllVerticesData(vertexData, false);
  82776. newMesh.computeWorldMatrix(true);
  82777. // Apply submeshes
  82778. newMesh.subMeshes = [];
  82779. var index = 0;
  82780. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82781. var meshID = meshes[meshIndex];
  82782. var mesh = gltfRuntime.meshes[meshID];
  82783. if (!mesh) {
  82784. continue;
  82785. }
  82786. for (var i = 0; i < mesh.primitives.length; i++) {
  82787. if (mesh.primitives[i].mode !== 4) {
  82788. //continue;
  82789. }
  82790. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  82791. index++;
  82792. }
  82793. }
  82794. // Finish
  82795. return newMesh;
  82796. };
  82797. /**
  82798. * Configure node transformation from position, rotation and scaling
  82799. */
  82800. var configureNode = function (newNode, position, rotation, scaling) {
  82801. if (newNode.position) {
  82802. newNode.position = position;
  82803. }
  82804. if (newNode.rotationQuaternion || newNode.rotation) {
  82805. newNode.rotationQuaternion = rotation;
  82806. }
  82807. if (newNode.scaling) {
  82808. newNode.scaling = scaling;
  82809. }
  82810. };
  82811. /**
  82812. * Configures node from transformation matrix
  82813. */
  82814. var configureNodeFromMatrix = function (newNode, node, parent) {
  82815. if (node.matrix) {
  82816. var position = new BABYLON.Vector3(0, 0, 0);
  82817. var rotation = new BABYLON.Quaternion();
  82818. var scaling = new BABYLON.Vector3(0, 0, 0);
  82819. var mat = BABYLON.Matrix.FromArray(node.matrix);
  82820. mat.decompose(scaling, rotation, position);
  82821. configureNode(newNode, position, rotation, scaling);
  82822. }
  82823. else if (node.translation && node.rotation && node.scale) {
  82824. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  82825. }
  82826. newNode.computeWorldMatrix(true);
  82827. };
  82828. /**
  82829. * Imports a node
  82830. */
  82831. var importNode = function (gltfRuntime, node, id, parent) {
  82832. var lastNode = null;
  82833. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  82834. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  82835. return null;
  82836. }
  82837. }
  82838. // Meshes
  82839. if (node.skin) {
  82840. if (node.meshes) {
  82841. var skin = gltfRuntime.skins[node.skin];
  82842. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  82843. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  82844. if (newMesh.skeleton === null) {
  82845. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  82846. if (!skin.babylonSkeleton) {
  82847. skin.babylonSkeleton = newMesh.skeleton;
  82848. }
  82849. }
  82850. lastNode = newMesh;
  82851. }
  82852. }
  82853. else if (node.meshes) {
  82854. /**
  82855. * Improve meshes property
  82856. */
  82857. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  82858. lastNode = newMesh;
  82859. }
  82860. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  82861. var light = gltfRuntime.lights[node.light];
  82862. if (light) {
  82863. if (light.type === "ambient") {
  82864. var ambienLight = light[light.type];
  82865. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82866. hemiLight.name = node.name || "";
  82867. if (ambienLight.color) {
  82868. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  82869. }
  82870. lastNode = hemiLight;
  82871. }
  82872. else if (light.type === "directional") {
  82873. var directionalLight = light[light.type];
  82874. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82875. dirLight.name = node.name || "";
  82876. if (directionalLight.color) {
  82877. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  82878. }
  82879. lastNode = dirLight;
  82880. }
  82881. else if (light.type === "point") {
  82882. var pointLight = light[light.type];
  82883. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82884. ptLight.name = node.name || "";
  82885. if (pointLight.color) {
  82886. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  82887. }
  82888. lastNode = ptLight;
  82889. }
  82890. else if (light.type === "spot") {
  82891. var spotLight = light[light.type];
  82892. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  82893. spLight.name = node.name || "";
  82894. if (spotLight.color) {
  82895. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  82896. }
  82897. if (spotLight.fallOfAngle) {
  82898. spLight.angle = spotLight.fallOfAngle;
  82899. }
  82900. if (spotLight.fallOffExponent) {
  82901. spLight.exponent = spotLight.fallOffExponent;
  82902. }
  82903. lastNode = spLight;
  82904. }
  82905. }
  82906. }
  82907. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  82908. var camera = gltfRuntime.cameras[node.camera];
  82909. if (camera) {
  82910. if (camera.type === "orthographic") {
  82911. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82912. orthoCamera.name = node.name || "";
  82913. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  82914. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  82915. lastNode = orthoCamera;
  82916. }
  82917. else if (camera.type === "perspective") {
  82918. var perspectiveCamera = camera[camera.type];
  82919. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  82920. persCamera.name = node.name || "";
  82921. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  82922. if (!perspectiveCamera.aspectRatio) {
  82923. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  82924. }
  82925. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  82926. persCamera.maxZ = perspectiveCamera.zfar;
  82927. persCamera.minZ = perspectiveCamera.znear;
  82928. }
  82929. lastNode = persCamera;
  82930. }
  82931. }
  82932. }
  82933. // Empty node
  82934. if (!node.jointName) {
  82935. if (node.babylonNode) {
  82936. return node.babylonNode;
  82937. }
  82938. else if (lastNode === null) {
  82939. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82940. node.babylonNode = dummy;
  82941. lastNode = dummy;
  82942. }
  82943. }
  82944. if (lastNode !== null) {
  82945. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  82946. configureNodeFromMatrix(lastNode, node, parent);
  82947. }
  82948. else {
  82949. var translation = node.translation || [0, 0, 0];
  82950. var rotation = node.rotation || [0, 0, 0, 1];
  82951. var scale = node.scale || [1, 1, 1];
  82952. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  82953. }
  82954. lastNode.updateCache(true);
  82955. node.babylonNode = lastNode;
  82956. }
  82957. return lastNode;
  82958. };
  82959. /**
  82960. * Traverses nodes and creates them
  82961. */
  82962. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  82963. if (meshIncluded === void 0) { meshIncluded = false; }
  82964. var node = gltfRuntime.nodes[id];
  82965. var newNode = null;
  82966. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  82967. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  82968. meshIncluded = true;
  82969. }
  82970. else {
  82971. meshIncluded = false;
  82972. }
  82973. }
  82974. else {
  82975. meshIncluded = true;
  82976. }
  82977. if (!node.jointName && meshIncluded) {
  82978. newNode = importNode(gltfRuntime, node, id, parent);
  82979. if (newNode !== null) {
  82980. newNode.id = id;
  82981. newNode.parent = parent;
  82982. }
  82983. }
  82984. if (node.children) {
  82985. for (var i = 0; i < node.children.length; i++) {
  82986. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  82987. }
  82988. }
  82989. };
  82990. /**
  82991. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  82992. */
  82993. var postLoad = function (gltfRuntime) {
  82994. // Nodes
  82995. var currentScene = gltfRuntime.currentScene;
  82996. if (currentScene) {
  82997. for (var i = 0; i < currentScene.nodes.length; i++) {
  82998. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  82999. }
  83000. }
  83001. else {
  83002. for (var thing in gltfRuntime.scenes) {
  83003. currentScene = gltfRuntime.scenes[thing];
  83004. for (var i = 0; i < currentScene.nodes.length; i++) {
  83005. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83006. }
  83007. }
  83008. }
  83009. // Set animations
  83010. loadAnimations(gltfRuntime);
  83011. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  83012. var skeleton = gltfRuntime.scene.skeletons[i];
  83013. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  83014. }
  83015. };
  83016. /**
  83017. * onBind shaderrs callback to set uniforms and matrices
  83018. */
  83019. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  83020. var materialValues = material.values || technique.parameters;
  83021. for (var unif in unTreatedUniforms) {
  83022. var uniform = unTreatedUniforms[unif];
  83023. var type = uniform.type;
  83024. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  83025. if (uniform.semantic && !uniform.source && !uniform.node) {
  83026. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  83027. }
  83028. else if (uniform.semantic && (uniform.source || uniform.node)) {
  83029. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  83030. if (source === null) {
  83031. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  83032. }
  83033. if (source === null) {
  83034. continue;
  83035. }
  83036. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  83037. }
  83038. }
  83039. else {
  83040. var value = materialValues[technique.uniforms[unif]];
  83041. if (!value) {
  83042. continue;
  83043. }
  83044. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83045. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  83046. if (texture === null || texture === undefined) {
  83047. continue;
  83048. }
  83049. shaderMaterial.getEffect().setTexture(unif, texture);
  83050. }
  83051. else {
  83052. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  83053. }
  83054. }
  83055. }
  83056. onSuccess(shaderMaterial);
  83057. };
  83058. /**
  83059. * Prepare uniforms to send the only one time
  83060. * Loads the appropriate textures
  83061. */
  83062. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  83063. var materialValues = material.values || technique.parameters;
  83064. var techniqueUniforms = technique.uniforms;
  83065. /**
  83066. * Prepare values here (not matrices)
  83067. */
  83068. for (var unif in unTreatedUniforms) {
  83069. var uniform = unTreatedUniforms[unif];
  83070. var type = uniform.type;
  83071. var value = materialValues[techniqueUniforms[unif]];
  83072. if (value === undefined) {
  83073. // In case the value is the same for all materials
  83074. value = uniform.value;
  83075. }
  83076. if (!value) {
  83077. continue;
  83078. }
  83079. var onLoadTexture = function (uniformName) {
  83080. return function (texture) {
  83081. if (uniform.value && uniformName) {
  83082. // Static uniform
  83083. shaderMaterial.setTexture(uniformName, texture);
  83084. delete unTreatedUniforms[uniformName];
  83085. }
  83086. };
  83087. };
  83088. // Texture (sampler2D)
  83089. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83090. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  83091. }
  83092. else {
  83093. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  83094. // Static uniform
  83095. delete unTreatedUniforms[unif];
  83096. }
  83097. }
  83098. }
  83099. };
  83100. /**
  83101. * Shader compilation failed
  83102. */
  83103. var onShaderCompileError = function (program, shaderMaterial, onError) {
  83104. return function (effect, error) {
  83105. shaderMaterial.dispose(true);
  83106. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  83107. };
  83108. };
  83109. /**
  83110. * Shader compilation success
  83111. */
  83112. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  83113. return function (_) {
  83114. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  83115. shaderMaterial.onBind = function (mesh) {
  83116. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  83117. };
  83118. };
  83119. };
  83120. /**
  83121. * Returns the appropriate uniform if already handled by babylon
  83122. */
  83123. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  83124. for (var unif in technique.uniforms) {
  83125. var uniform = technique.uniforms[unif];
  83126. var uniformParameter = technique.parameters[uniform];
  83127. if (tokenizer.currentIdentifier === unif) {
  83128. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  83129. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83130. if (transformIndex !== -1) {
  83131. delete unTreatedUniforms[unif];
  83132. return babylonTransforms[transformIndex];
  83133. }
  83134. }
  83135. }
  83136. }
  83137. return tokenizer.currentIdentifier;
  83138. };
  83139. /**
  83140. * All shaders loaded. Create materials one by one
  83141. */
  83142. var importMaterials = function (gltfRuntime) {
  83143. // Create materials
  83144. for (var mat in gltfRuntime.materials) {
  83145. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  83146. }
  83147. };
  83148. /**
  83149. * Implementation of the base glTF spec
  83150. */
  83151. var GLTFLoaderBase = /** @class */ (function () {
  83152. function GLTFLoaderBase() {
  83153. }
  83154. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  83155. var gltfRuntime = {
  83156. extensions: {},
  83157. accessors: {},
  83158. buffers: {},
  83159. bufferViews: {},
  83160. meshes: {},
  83161. lights: {},
  83162. cameras: {},
  83163. nodes: {},
  83164. images: {},
  83165. textures: {},
  83166. shaders: {},
  83167. programs: {},
  83168. samplers: {},
  83169. techniques: {},
  83170. materials: {},
  83171. animations: {},
  83172. skins: {},
  83173. extensionsUsed: [],
  83174. scenes: {},
  83175. buffersCount: 0,
  83176. shaderscount: 0,
  83177. scene: scene,
  83178. rootUrl: rootUrl,
  83179. loadedBufferCount: 0,
  83180. loadedBufferViews: {},
  83181. loadedShaderCount: 0,
  83182. importOnlyMeshes: false,
  83183. dummyNodes: []
  83184. };
  83185. // Parse
  83186. if (parsedData.extensions) {
  83187. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  83188. }
  83189. if (parsedData.extensionsUsed) {
  83190. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  83191. }
  83192. if (parsedData.buffers) {
  83193. parseBuffers(parsedData.buffers, gltfRuntime);
  83194. }
  83195. if (parsedData.bufferViews) {
  83196. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  83197. }
  83198. if (parsedData.accessors) {
  83199. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  83200. }
  83201. if (parsedData.meshes) {
  83202. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  83203. }
  83204. if (parsedData.lights) {
  83205. parseObject(parsedData.lights, "lights", gltfRuntime);
  83206. }
  83207. if (parsedData.cameras) {
  83208. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  83209. }
  83210. if (parsedData.nodes) {
  83211. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  83212. }
  83213. if (parsedData.images) {
  83214. parseObject(parsedData.images, "images", gltfRuntime);
  83215. }
  83216. if (parsedData.textures) {
  83217. parseObject(parsedData.textures, "textures", gltfRuntime);
  83218. }
  83219. if (parsedData.shaders) {
  83220. parseShaders(parsedData.shaders, gltfRuntime);
  83221. }
  83222. if (parsedData.programs) {
  83223. parseObject(parsedData.programs, "programs", gltfRuntime);
  83224. }
  83225. if (parsedData.samplers) {
  83226. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  83227. }
  83228. if (parsedData.techniques) {
  83229. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  83230. }
  83231. if (parsedData.materials) {
  83232. parseObject(parsedData.materials, "materials", gltfRuntime);
  83233. }
  83234. if (parsedData.animations) {
  83235. parseObject(parsedData.animations, "animations", gltfRuntime);
  83236. }
  83237. if (parsedData.skins) {
  83238. parseObject(parsedData.skins, "skins", gltfRuntime);
  83239. }
  83240. if (parsedData.scenes) {
  83241. gltfRuntime.scenes = parsedData.scenes;
  83242. }
  83243. if (parsedData.scene && parsedData.scenes) {
  83244. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  83245. }
  83246. return gltfRuntime;
  83247. };
  83248. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83249. var buffer = gltfRuntime.buffers[id];
  83250. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  83251. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  83252. }
  83253. else {
  83254. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  83255. if (request) {
  83256. onError(request.status + " " + request.statusText);
  83257. }
  83258. });
  83259. }
  83260. };
  83261. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83262. var texture = gltfRuntime.textures[id];
  83263. if (!texture || !texture.source) {
  83264. onError("");
  83265. return;
  83266. }
  83267. if (texture.babylonTexture) {
  83268. onSuccess(null);
  83269. return;
  83270. }
  83271. var source = gltfRuntime.images[texture.source];
  83272. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  83273. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  83274. }
  83275. else {
  83276. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  83277. if (request) {
  83278. onError(request.status + " " + request.statusText);
  83279. }
  83280. });
  83281. }
  83282. };
  83283. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83284. var texture = gltfRuntime.textures[id];
  83285. if (texture.babylonTexture) {
  83286. onSuccess(texture.babylonTexture);
  83287. return;
  83288. }
  83289. var sampler = gltfRuntime.samplers[texture.sampler];
  83290. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  83291. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  83292. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  83293. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  83294. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83295. var blob = new Blob([buffer]);
  83296. var blobURL = URL.createObjectURL(blob);
  83297. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  83298. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  83299. if (sampler.wrapS !== undefined) {
  83300. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  83301. }
  83302. if (sampler.wrapT !== undefined) {
  83303. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  83304. }
  83305. newTexture.name = id;
  83306. texture.babylonTexture = newTexture;
  83307. onSuccess(newTexture);
  83308. };
  83309. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83310. var shader = gltfRuntime.shaders[id];
  83311. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  83312. var shaderString = atob(shader.uri.split(",")[1]);
  83313. onSuccess(shaderString);
  83314. }
  83315. else {
  83316. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  83317. if (request) {
  83318. onError(request.status + " " + request.statusText);
  83319. }
  83320. });
  83321. }
  83322. };
  83323. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83324. var material = gltfRuntime.materials[id];
  83325. if (!material.technique) {
  83326. if (onError) {
  83327. onError("No technique found.");
  83328. }
  83329. return;
  83330. }
  83331. var technique = gltfRuntime.techniques[material.technique];
  83332. if (!technique) {
  83333. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83334. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  83335. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83336. onSuccess(defaultMaterial);
  83337. return;
  83338. }
  83339. var program = gltfRuntime.programs[technique.program];
  83340. var states = technique.states;
  83341. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  83342. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  83343. var newVertexShader = "";
  83344. var newPixelShader = "";
  83345. var vertexTokenizer = new Tokenizer(vertexShader);
  83346. var pixelTokenizer = new Tokenizer(pixelShader);
  83347. var unTreatedUniforms = {};
  83348. var uniforms = [];
  83349. var attributes = [];
  83350. var samplers = [];
  83351. // Fill uniform, sampler2D and attributes
  83352. for (var unif in technique.uniforms) {
  83353. var uniform = technique.uniforms[unif];
  83354. var uniformParameter = technique.parameters[uniform];
  83355. unTreatedUniforms[unif] = uniformParameter;
  83356. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  83357. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83358. if (transformIndex !== -1) {
  83359. uniforms.push(babylonTransforms[transformIndex]);
  83360. delete unTreatedUniforms[unif];
  83361. }
  83362. else {
  83363. uniforms.push(unif);
  83364. }
  83365. }
  83366. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  83367. samplers.push(unif);
  83368. }
  83369. else {
  83370. uniforms.push(unif);
  83371. }
  83372. }
  83373. for (var attr in technique.attributes) {
  83374. var attribute = technique.attributes[attr];
  83375. var attributeParameter = technique.parameters[attribute];
  83376. if (attributeParameter.semantic) {
  83377. attributes.push(getAttribute(attributeParameter));
  83378. }
  83379. }
  83380. // Configure vertex shader
  83381. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  83382. var tokenType = vertexTokenizer.currentToken;
  83383. if (tokenType !== ETokenType.IDENTIFIER) {
  83384. newVertexShader += vertexTokenizer.currentString;
  83385. continue;
  83386. }
  83387. var foundAttribute = false;
  83388. for (var attr in technique.attributes) {
  83389. var attribute = technique.attributes[attr];
  83390. var attributeParameter = technique.parameters[attribute];
  83391. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  83392. newVertexShader += getAttribute(attributeParameter);
  83393. foundAttribute = true;
  83394. break;
  83395. }
  83396. }
  83397. if (foundAttribute) {
  83398. continue;
  83399. }
  83400. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  83401. }
  83402. // Configure pixel shader
  83403. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  83404. var tokenType = pixelTokenizer.currentToken;
  83405. if (tokenType !== ETokenType.IDENTIFIER) {
  83406. newPixelShader += pixelTokenizer.currentString;
  83407. continue;
  83408. }
  83409. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  83410. }
  83411. // Create shader material
  83412. var shaderPath = {
  83413. vertex: program.vertexShader + id,
  83414. fragment: program.fragmentShader + id
  83415. };
  83416. var options = {
  83417. attributes: attributes,
  83418. uniforms: uniforms,
  83419. samplers: samplers,
  83420. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  83421. };
  83422. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  83423. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  83424. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  83425. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  83426. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  83427. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83428. if (states && states.functions) {
  83429. var functions = states.functions;
  83430. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  83431. shaderMaterial.backFaceCulling = false;
  83432. }
  83433. var blendFunc = functions.blendFuncSeparate;
  83434. if (blendFunc) {
  83435. 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) {
  83436. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  83437. }
  83438. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83439. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83440. }
  83441. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83442. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  83443. }
  83444. 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) {
  83445. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  83446. }
  83447. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83448. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  83449. }
  83450. 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) {
  83451. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  83452. }
  83453. }
  83454. }
  83455. };
  83456. return GLTFLoaderBase;
  83457. }());
  83458. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  83459. /**
  83460. * glTF V1 Loader
  83461. */
  83462. var GLTFLoader = /** @class */ (function () {
  83463. function GLTFLoader() {
  83464. // #region Stubs for IGLTFLoader interface
  83465. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  83466. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  83467. this.compileMaterials = false;
  83468. this.useClipPlane = false;
  83469. this.compileShadowGenerators = false;
  83470. this.onDisposeObservable = new BABYLON.Observable();
  83471. this.onMeshLoadedObservable = new BABYLON.Observable();
  83472. this.onTextureLoadedObservable = new BABYLON.Observable();
  83473. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83474. this.onCompleteObservable = new BABYLON.Observable();
  83475. }
  83476. GLTFLoader.RegisterExtension = function (extension) {
  83477. if (GLTFLoader.Extensions[extension.name]) {
  83478. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  83479. return;
  83480. }
  83481. GLTFLoader.Extensions[extension.name] = extension;
  83482. };
  83483. GLTFLoader.prototype.dispose = function () { };
  83484. // #endregion
  83485. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83486. var _this = this;
  83487. scene.useRightHandedSystem = true;
  83488. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83489. gltfRuntime.importOnlyMeshes = true;
  83490. if (meshesNames === "") {
  83491. gltfRuntime.importMeshesNames = [];
  83492. }
  83493. else if (typeof meshesNames === "string") {
  83494. gltfRuntime.importMeshesNames = [meshesNames];
  83495. }
  83496. else if (meshesNames && !(meshesNames instanceof Array)) {
  83497. gltfRuntime.importMeshesNames = [meshesNames];
  83498. }
  83499. else {
  83500. gltfRuntime.importMeshesNames = [];
  83501. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  83502. }
  83503. // Create nodes
  83504. _this._createNodes(gltfRuntime);
  83505. var meshes = new Array();
  83506. var skeletons = new Array();
  83507. // Fill arrays of meshes and skeletons
  83508. for (var nde in gltfRuntime.nodes) {
  83509. var node = gltfRuntime.nodes[nde];
  83510. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  83511. meshes.push(node.babylonNode);
  83512. }
  83513. }
  83514. for (var skl in gltfRuntime.skins) {
  83515. var skin = gltfRuntime.skins[skl];
  83516. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  83517. skeletons.push(skin.babylonSkeleton);
  83518. }
  83519. }
  83520. // Load buffers, shaders, materials, etc.
  83521. _this._loadBuffersAsync(gltfRuntime, function () {
  83522. _this._loadShadersAsync(gltfRuntime, function () {
  83523. importMaterials(gltfRuntime);
  83524. postLoad(gltfRuntime);
  83525. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83526. onSuccess(meshes, [], skeletons);
  83527. }
  83528. });
  83529. }, onProgress);
  83530. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83531. onSuccess(meshes, [], skeletons);
  83532. }
  83533. }, onError);
  83534. return true;
  83535. };
  83536. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83537. var _this = this;
  83538. scene.useRightHandedSystem = true;
  83539. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83540. // Load runtime extensios
  83541. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  83542. // Create nodes
  83543. _this._createNodes(gltfRuntime);
  83544. // Load buffers, shaders, materials, etc.
  83545. _this._loadBuffersAsync(gltfRuntime, function () {
  83546. _this._loadShadersAsync(gltfRuntime, function () {
  83547. importMaterials(gltfRuntime);
  83548. postLoad(gltfRuntime);
  83549. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  83550. onSuccess();
  83551. }
  83552. });
  83553. });
  83554. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  83555. onSuccess();
  83556. }
  83557. }, onError);
  83558. }, onError);
  83559. };
  83560. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  83561. var hasShaders = false;
  83562. var processShader = function (sha, shader) {
  83563. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  83564. gltfRuntime.loadedShaderCount++;
  83565. if (shaderString) {
  83566. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  83567. }
  83568. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  83569. onload();
  83570. }
  83571. }, function () {
  83572. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  83573. });
  83574. };
  83575. for (var sha in gltfRuntime.shaders) {
  83576. hasShaders = true;
  83577. var shader = gltfRuntime.shaders[sha];
  83578. if (shader) {
  83579. processShader.bind(this, sha, shader)();
  83580. }
  83581. else {
  83582. BABYLON.Tools.Error("No shader named: " + sha);
  83583. }
  83584. }
  83585. if (!hasShaders) {
  83586. onload();
  83587. }
  83588. };
  83589. ;
  83590. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  83591. var hasBuffers = false;
  83592. var processBuffer = function (buf, buffer) {
  83593. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  83594. gltfRuntime.loadedBufferCount++;
  83595. if (bufferView) {
  83596. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  83597. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  83598. }
  83599. gltfRuntime.loadedBufferViews[buf] = bufferView;
  83600. }
  83601. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  83602. onLoad();
  83603. }
  83604. }, function () {
  83605. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  83606. });
  83607. };
  83608. for (var buf in gltfRuntime.buffers) {
  83609. hasBuffers = true;
  83610. var buffer = gltfRuntime.buffers[buf];
  83611. if (buffer) {
  83612. processBuffer.bind(this, buf, buffer)();
  83613. }
  83614. else {
  83615. BABYLON.Tools.Error("No buffer named: " + buf);
  83616. }
  83617. }
  83618. if (!hasBuffers) {
  83619. onLoad();
  83620. }
  83621. };
  83622. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  83623. var currentScene = gltfRuntime.currentScene;
  83624. if (currentScene) {
  83625. // Only one scene even if multiple scenes are defined
  83626. for (var i = 0; i < currentScene.nodes.length; i++) {
  83627. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83628. }
  83629. }
  83630. else {
  83631. // Load all scenes
  83632. for (var thing in gltfRuntime.scenes) {
  83633. currentScene = gltfRuntime.scenes[thing];
  83634. for (var i = 0; i < currentScene.nodes.length; i++) {
  83635. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83636. }
  83637. }
  83638. }
  83639. };
  83640. GLTFLoader.Extensions = {};
  83641. return GLTFLoader;
  83642. }());
  83643. GLTF1.GLTFLoader = GLTFLoader;
  83644. ;
  83645. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  83646. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83647. })(BABYLON || (BABYLON = {}));
  83648. //# sourceMappingURL=babylon.glTFLoader.js.map
  83649. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83650. var BABYLON;
  83651. (function (BABYLON) {
  83652. var GLTF1;
  83653. (function (GLTF1) {
  83654. /**
  83655. * Utils functions for GLTF
  83656. */
  83657. var GLTFUtils = /** @class */ (function () {
  83658. function GLTFUtils() {
  83659. }
  83660. /**
  83661. * Sets the given "parameter" matrix
  83662. * @param scene: the {BABYLON.Scene} object
  83663. * @param source: the source node where to pick the matrix
  83664. * @param parameter: the GLTF technique parameter
  83665. * @param uniformName: the name of the shader's uniform
  83666. * @param shaderMaterial: the shader material
  83667. */
  83668. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  83669. var mat = null;
  83670. if (parameter.semantic === "MODEL") {
  83671. mat = source.getWorldMatrix();
  83672. }
  83673. else if (parameter.semantic === "PROJECTION") {
  83674. mat = scene.getProjectionMatrix();
  83675. }
  83676. else if (parameter.semantic === "VIEW") {
  83677. mat = scene.getViewMatrix();
  83678. }
  83679. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  83680. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  83681. }
  83682. else if (parameter.semantic === "MODELVIEW") {
  83683. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  83684. }
  83685. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  83686. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  83687. }
  83688. else if (parameter.semantic === "MODELINVERSE") {
  83689. mat = source.getWorldMatrix().invert();
  83690. }
  83691. else if (parameter.semantic === "VIEWINVERSE") {
  83692. mat = scene.getViewMatrix().invert();
  83693. }
  83694. else if (parameter.semantic === "PROJECTIONINVERSE") {
  83695. mat = scene.getProjectionMatrix().invert();
  83696. }
  83697. else if (parameter.semantic === "MODELVIEWINVERSE") {
  83698. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  83699. }
  83700. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  83701. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  83702. }
  83703. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  83704. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  83705. }
  83706. else {
  83707. debugger;
  83708. }
  83709. if (mat) {
  83710. switch (parameter.type) {
  83711. case GLTF1.EParameterType.FLOAT_MAT2:
  83712. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  83713. break;
  83714. case GLTF1.EParameterType.FLOAT_MAT3:
  83715. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  83716. break;
  83717. case GLTF1.EParameterType.FLOAT_MAT4:
  83718. shaderMaterial.setMatrix(uniformName, mat);
  83719. break;
  83720. default: break;
  83721. }
  83722. }
  83723. };
  83724. /**
  83725. * Sets the given "parameter" matrix
  83726. * @param shaderMaterial: the shader material
  83727. * @param uniform: the name of the shader's uniform
  83728. * @param value: the value of the uniform
  83729. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  83730. */
  83731. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  83732. switch (type) {
  83733. case GLTF1.EParameterType.FLOAT:
  83734. shaderMaterial.setFloat(uniform, value);
  83735. return true;
  83736. case GLTF1.EParameterType.FLOAT_VEC2:
  83737. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  83738. return true;
  83739. case GLTF1.EParameterType.FLOAT_VEC3:
  83740. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  83741. return true;
  83742. case GLTF1.EParameterType.FLOAT_VEC4:
  83743. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  83744. return true;
  83745. default: return false;
  83746. }
  83747. };
  83748. /**
  83749. * If the uri is a base64 string
  83750. * @param uri: the uri to test
  83751. */
  83752. GLTFUtils.IsBase64 = function (uri) {
  83753. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  83754. };
  83755. /**
  83756. * Decode the base64 uri
  83757. * @param uri: the uri to decode
  83758. */
  83759. GLTFUtils.DecodeBase64 = function (uri) {
  83760. var decodedString = atob(uri.split(",")[1]);
  83761. var bufferLength = decodedString.length;
  83762. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  83763. for (var i = 0; i < bufferLength; i++) {
  83764. bufferView[i] = decodedString.charCodeAt(i);
  83765. }
  83766. return bufferView.buffer;
  83767. };
  83768. /**
  83769. * Returns the wrap mode of the texture
  83770. * @param mode: the mode value
  83771. */
  83772. GLTFUtils.GetWrapMode = function (mode) {
  83773. switch (mode) {
  83774. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83775. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83776. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83777. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83778. }
  83779. };
  83780. /**
  83781. * Returns the byte stride giving an accessor
  83782. * @param accessor: the GLTF accessor objet
  83783. */
  83784. GLTFUtils.GetByteStrideFromType = function (accessor) {
  83785. // Needs this function since "byteStride" isn't requiered in glTF format
  83786. var type = accessor.type;
  83787. switch (type) {
  83788. case "VEC2": return 2;
  83789. case "VEC3": return 3;
  83790. case "VEC4": return 4;
  83791. case "MAT2": return 4;
  83792. case "MAT3": return 9;
  83793. case "MAT4": return 16;
  83794. default: return 1;
  83795. }
  83796. };
  83797. /**
  83798. * Returns the texture filter mode giving a mode value
  83799. * @param mode: the filter mode value
  83800. */
  83801. GLTFUtils.GetTextureFilterMode = function (mode) {
  83802. switch (mode) {
  83803. case GLTF1.ETextureFilterType.LINEAR:
  83804. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  83805. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  83806. case GLTF1.ETextureFilterType.NEAREST:
  83807. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  83808. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83809. }
  83810. };
  83811. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  83812. var byteOffset = bufferView.byteOffset + byteOffset;
  83813. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  83814. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  83815. throw new Error("Buffer access is out of range");
  83816. }
  83817. var buffer = loadedBufferView.buffer;
  83818. byteOffset += loadedBufferView.byteOffset;
  83819. switch (componentType) {
  83820. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  83821. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  83822. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  83823. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  83824. default: return new Float32Array(buffer, byteOffset, byteLength);
  83825. }
  83826. };
  83827. /**
  83828. * Returns a buffer from its accessor
  83829. * @param gltfRuntime: the GLTF runtime
  83830. * @param accessor: the GLTF accessor
  83831. */
  83832. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  83833. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  83834. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  83835. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  83836. };
  83837. /**
  83838. * Decodes a buffer view into a string
  83839. * @param view: the buffer view
  83840. */
  83841. GLTFUtils.DecodeBufferToText = function (view) {
  83842. var result = "";
  83843. var length = view.byteLength;
  83844. for (var i = 0; i < length; ++i) {
  83845. result += String.fromCharCode(view[i]);
  83846. }
  83847. return result;
  83848. };
  83849. /**
  83850. * Returns the default material of gltf. Related to
  83851. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  83852. * @param scene: the Babylon.js scene
  83853. */
  83854. GLTFUtils.GetDefaultMaterial = function (scene) {
  83855. if (!GLTFUtils._DefaultMaterial) {
  83856. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  83857. "precision highp float;",
  83858. "",
  83859. "uniform mat4 worldView;",
  83860. "uniform mat4 projection;",
  83861. "",
  83862. "attribute vec3 position;",
  83863. "",
  83864. "void main(void)",
  83865. "{",
  83866. " gl_Position = projection * worldView * vec4(position, 1.0);",
  83867. "}"
  83868. ].join("\n");
  83869. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  83870. "precision highp float;",
  83871. "",
  83872. "uniform vec4 u_emission;",
  83873. "",
  83874. "void main(void)",
  83875. "{",
  83876. " gl_FragColor = u_emission;",
  83877. "}"
  83878. ].join("\n");
  83879. var shaderPath = {
  83880. vertex: "GLTFDefaultMaterial",
  83881. fragment: "GLTFDefaultMaterial"
  83882. };
  83883. var options = {
  83884. attributes: ["position"],
  83885. uniforms: ["worldView", "projection", "u_emission"],
  83886. samplers: new Array(),
  83887. needAlphaBlending: false
  83888. };
  83889. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  83890. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  83891. }
  83892. return GLTFUtils._DefaultMaterial;
  83893. };
  83894. // The GLTF default material
  83895. GLTFUtils._DefaultMaterial = null;
  83896. return GLTFUtils;
  83897. }());
  83898. GLTF1.GLTFUtils = GLTFUtils;
  83899. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83900. })(BABYLON || (BABYLON = {}));
  83901. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  83902. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83903. var BABYLON;
  83904. (function (BABYLON) {
  83905. var GLTF1;
  83906. (function (GLTF1) {
  83907. var GLTFLoaderExtension = /** @class */ (function () {
  83908. function GLTFLoaderExtension(name) {
  83909. this._name = name;
  83910. }
  83911. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  83912. get: function () {
  83913. return this._name;
  83914. },
  83915. enumerable: true,
  83916. configurable: true
  83917. });
  83918. /**
  83919. * Defines an override for loading the runtime
  83920. * Return true to stop further extensions from loading the runtime
  83921. */
  83922. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  83923. return false;
  83924. };
  83925. /**
  83926. * Defines an onverride for creating gltf runtime
  83927. * Return true to stop further extensions from creating the runtime
  83928. */
  83929. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  83930. return false;
  83931. };
  83932. /**
  83933. * Defines an override for loading buffers
  83934. * Return true to stop further extensions from loading this buffer
  83935. */
  83936. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83937. return false;
  83938. };
  83939. /**
  83940. * Defines an override for loading texture buffers
  83941. * Return true to stop further extensions from loading this texture data
  83942. */
  83943. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83944. return false;
  83945. };
  83946. /**
  83947. * Defines an override for creating textures
  83948. * Return true to stop further extensions from loading this texture
  83949. */
  83950. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83951. return false;
  83952. };
  83953. /**
  83954. * Defines an override for loading shader strings
  83955. * Return true to stop further extensions from loading this shader data
  83956. */
  83957. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83958. return false;
  83959. };
  83960. /**
  83961. * Defines an override for loading materials
  83962. * Return true to stop further extensions from loading this material
  83963. */
  83964. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83965. return false;
  83966. };
  83967. // ---------
  83968. // Utilities
  83969. // ---------
  83970. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  83971. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83972. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  83973. }, function () {
  83974. setTimeout(function () {
  83975. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  83976. });
  83977. });
  83978. };
  83979. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  83980. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83981. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  83982. }, function () {
  83983. setTimeout(function () {
  83984. onSuccess();
  83985. });
  83986. });
  83987. };
  83988. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83989. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  83990. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  83991. }, function () {
  83992. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  83993. });
  83994. };
  83995. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  83996. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  83997. };
  83998. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83999. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84000. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84001. }, function () {
  84002. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84003. });
  84004. };
  84005. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84006. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84007. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84008. }, function () {
  84009. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84010. });
  84011. };
  84012. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84013. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84014. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84015. }, function () {
  84016. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84017. });
  84018. };
  84019. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84020. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84021. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84022. }, function () {
  84023. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84024. });
  84025. };
  84026. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  84027. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  84028. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  84029. if (func(loaderExtension)) {
  84030. return;
  84031. }
  84032. }
  84033. defaultFunc();
  84034. };
  84035. return GLTFLoaderExtension;
  84036. }());
  84037. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  84038. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84039. })(BABYLON || (BABYLON = {}));
  84040. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84041. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84042. var BABYLON;
  84043. (function (BABYLON) {
  84044. var GLTF1;
  84045. (function (GLTF1) {
  84046. var BinaryExtensionBufferName = "binary_glTF";
  84047. ;
  84048. ;
  84049. var GLTFBinaryExtension = /** @class */ (function (_super) {
  84050. __extends(GLTFBinaryExtension, _super);
  84051. function GLTFBinaryExtension() {
  84052. return _super.call(this, "KHR_binary_glTF") || this;
  84053. }
  84054. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84055. var extensionsUsed = data.json.extensionsUsed;
  84056. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  84057. return false;
  84058. }
  84059. this._bin = data.bin;
  84060. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84061. return true;
  84062. };
  84063. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84064. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  84065. return false;
  84066. }
  84067. if (id !== BinaryExtensionBufferName) {
  84068. return false;
  84069. }
  84070. onSuccess(this._bin);
  84071. return true;
  84072. };
  84073. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84074. var texture = gltfRuntime.textures[id];
  84075. var source = gltfRuntime.images[texture.source];
  84076. if (!source.extensions || !(this.name in source.extensions)) {
  84077. return false;
  84078. }
  84079. var sourceExt = source.extensions[this.name];
  84080. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  84081. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84082. onSuccess(buffer);
  84083. return true;
  84084. };
  84085. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84086. var shader = gltfRuntime.shaders[id];
  84087. if (!shader.extensions || !(this.name in shader.extensions)) {
  84088. return false;
  84089. }
  84090. var binaryExtensionShader = shader.extensions[this.name];
  84091. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  84092. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84093. setTimeout(function () {
  84094. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  84095. onSuccess(shaderString);
  84096. });
  84097. return true;
  84098. };
  84099. return GLTFBinaryExtension;
  84100. }(GLTF1.GLTFLoaderExtension));
  84101. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  84102. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  84103. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84104. })(BABYLON || (BABYLON = {}));
  84105. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  84106. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84107. var BABYLON;
  84108. (function (BABYLON) {
  84109. var GLTF1;
  84110. (function (GLTF1) {
  84111. ;
  84112. ;
  84113. ;
  84114. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  84115. __extends(GLTFMaterialsCommonExtension, _super);
  84116. function GLTFMaterialsCommonExtension() {
  84117. return _super.call(this, "KHR_materials_common") || this;
  84118. }
  84119. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84120. if (!gltfRuntime.extensions)
  84121. return false;
  84122. var extension = gltfRuntime.extensions[this.name];
  84123. if (!extension)
  84124. return false;
  84125. // Create lights
  84126. var lights = extension.lights;
  84127. if (lights) {
  84128. for (var thing in lights) {
  84129. var light = lights[thing];
  84130. switch (light.type) {
  84131. case "ambient":
  84132. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  84133. var ambient = light.ambient;
  84134. if (ambient) {
  84135. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  84136. }
  84137. break;
  84138. case "point":
  84139. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  84140. var point = light.point;
  84141. if (point) {
  84142. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  84143. }
  84144. break;
  84145. case "directional":
  84146. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  84147. var directional = light.directional;
  84148. if (directional) {
  84149. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  84150. }
  84151. break;
  84152. case "spot":
  84153. var spot = light.spot;
  84154. if (spot) {
  84155. 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);
  84156. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  84157. }
  84158. break;
  84159. default:
  84160. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  84161. break;
  84162. }
  84163. }
  84164. }
  84165. return false;
  84166. };
  84167. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84168. var material = gltfRuntime.materials[id];
  84169. if (!material || !material.extensions)
  84170. return false;
  84171. var extension = material.extensions[this.name];
  84172. if (!extension)
  84173. return false;
  84174. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  84175. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  84176. if (extension.technique === "CONSTANT") {
  84177. standardMaterial.disableLighting = true;
  84178. }
  84179. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  84180. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  84181. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  84182. // Ambient
  84183. if (typeof extension.values.ambient === "string") {
  84184. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  84185. }
  84186. else {
  84187. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  84188. }
  84189. // Diffuse
  84190. if (typeof extension.values.diffuse === "string") {
  84191. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  84192. }
  84193. else {
  84194. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  84195. }
  84196. // Emission
  84197. if (typeof extension.values.emission === "string") {
  84198. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  84199. }
  84200. else {
  84201. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  84202. }
  84203. // Specular
  84204. if (typeof extension.values.specular === "string") {
  84205. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  84206. }
  84207. else {
  84208. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  84209. }
  84210. return true;
  84211. };
  84212. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  84213. // Create buffer from texture url
  84214. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  84215. // Create texture from buffer
  84216. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  84217. }, onError);
  84218. };
  84219. return GLTFMaterialsCommonExtension;
  84220. }(GLTF1.GLTFLoaderExtension));
  84221. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  84222. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  84223. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84224. })(BABYLON || (BABYLON = {}));
  84225. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  84226. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84227. var BABYLON;
  84228. (function (BABYLON) {
  84229. var GLTF2;
  84230. (function (GLTF2) {
  84231. /**
  84232. * Enums
  84233. */
  84234. var EComponentType;
  84235. (function (EComponentType) {
  84236. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84237. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84238. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84239. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84240. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84241. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84242. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  84243. var EMeshPrimitiveMode;
  84244. (function (EMeshPrimitiveMode) {
  84245. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  84246. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  84247. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  84248. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  84249. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  84250. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  84251. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  84252. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  84253. var ETextureMagFilter;
  84254. (function (ETextureMagFilter) {
  84255. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  84256. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  84257. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  84258. var ETextureMinFilter;
  84259. (function (ETextureMinFilter) {
  84260. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  84261. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  84262. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84263. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84264. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84265. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84266. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  84267. var ETextureWrapMode;
  84268. (function (ETextureWrapMode) {
  84269. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84270. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84271. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84272. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  84273. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84274. })(BABYLON || (BABYLON = {}));
  84275. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84276. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84277. var BABYLON;
  84278. (function (BABYLON) {
  84279. var GLTF2;
  84280. (function (GLTF2) {
  84281. var GLTFLoaderTracker = /** @class */ (function () {
  84282. function GLTFLoaderTracker(onComplete) {
  84283. this._pendingCount = 0;
  84284. this._callback = onComplete;
  84285. }
  84286. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  84287. this._pendingCount++;
  84288. };
  84289. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  84290. if (--this._pendingCount === 0) {
  84291. this._callback();
  84292. }
  84293. };
  84294. return GLTFLoaderTracker;
  84295. }());
  84296. var GLTFLoader = /** @class */ (function () {
  84297. function GLTFLoader() {
  84298. this._disposed = false;
  84299. this._defaultSampler = {};
  84300. this._renderReady = false;
  84301. this._requests = new Array();
  84302. this._renderReadyObservable = new BABYLON.Observable();
  84303. // Count of pending work that needs to complete before the asset is rendered.
  84304. this._renderPendingCount = 0;
  84305. // Count of pending work that needs to complete before the loader is disposed.
  84306. this._loaderPendingCount = 0;
  84307. this._loaderTrackers = new Array();
  84308. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  84309. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  84310. this.compileMaterials = false;
  84311. this.useClipPlane = false;
  84312. this.compileShadowGenerators = false;
  84313. this.onDisposeObservable = new BABYLON.Observable();
  84314. this.onMeshLoadedObservable = new BABYLON.Observable();
  84315. this.onTextureLoadedObservable = new BABYLON.Observable();
  84316. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84317. this.onCompleteObservable = new BABYLON.Observable();
  84318. }
  84319. GLTFLoader.RegisterExtension = function (extension) {
  84320. if (GLTFLoader.Extensions[extension.name]) {
  84321. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  84322. return;
  84323. }
  84324. GLTFLoader.Extensions[extension.name] = extension;
  84325. // Keep the order of registration so that extensions registered first are called first.
  84326. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  84327. };
  84328. GLTFLoader.prototype.dispose = function () {
  84329. if (this._disposed) {
  84330. return;
  84331. }
  84332. this._disposed = true;
  84333. this._abortRequests();
  84334. this._releaseResources();
  84335. this.onDisposeObservable.notifyObservers(this);
  84336. };
  84337. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84338. var _this = this;
  84339. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  84340. if (onSuccess) {
  84341. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  84342. }
  84343. }, onProgress, onError);
  84344. };
  84345. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84346. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  84347. };
  84348. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84349. var _this = this;
  84350. this._babylonScene = scene;
  84351. this._rootUrl = rootUrl;
  84352. this._successCallback = onSuccess;
  84353. this._progressCallback = onProgress;
  84354. this._errorCallback = onError;
  84355. this._tryCatchOnError(function () {
  84356. _this._loadData(data);
  84357. _this._addPendingData(_this);
  84358. _this._loadDefaultScene(nodeNames);
  84359. _this._loadAnimations();
  84360. _this._removePendingData(_this);
  84361. });
  84362. };
  84363. GLTFLoader.prototype._onProgress = function () {
  84364. if (!this._progressCallback) {
  84365. return;
  84366. }
  84367. var lengthComputable = true;
  84368. var loaded = 0;
  84369. var total = 0;
  84370. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  84371. var request = _a[_i];
  84372. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  84373. return;
  84374. }
  84375. lengthComputable = lengthComputable && request._lengthComputable;
  84376. loaded += request._loaded;
  84377. total += request._total;
  84378. }
  84379. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  84380. };
  84381. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  84382. if (this._renderReady) {
  84383. func();
  84384. }
  84385. else {
  84386. this._renderReadyObservable.add(func);
  84387. }
  84388. };
  84389. GLTFLoader.prototype._onRenderReady = function () {
  84390. this._rootNode.babylonMesh.setEnabled(true);
  84391. this._startAnimations();
  84392. if (this._successCallback) {
  84393. this._successCallback();
  84394. }
  84395. this._renderReadyObservable.notifyObservers(this);
  84396. };
  84397. GLTFLoader.prototype._onComplete = function () {
  84398. this._abortRequests();
  84399. this._releaseResources();
  84400. this.onCompleteObservable.notifyObservers(this);
  84401. };
  84402. GLTFLoader.prototype._loadData = function (data) {
  84403. this._gltf = data.json;
  84404. // Assign the index of each object for convinience.
  84405. GLTFLoader._AssignIndices(this._gltf.accessors);
  84406. GLTFLoader._AssignIndices(this._gltf.animations);
  84407. GLTFLoader._AssignIndices(this._gltf.buffers);
  84408. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  84409. GLTFLoader._AssignIndices(this._gltf.images);
  84410. GLTFLoader._AssignIndices(this._gltf.materials);
  84411. GLTFLoader._AssignIndices(this._gltf.meshes);
  84412. GLTFLoader._AssignIndices(this._gltf.nodes);
  84413. GLTFLoader._AssignIndices(this._gltf.samplers);
  84414. GLTFLoader._AssignIndices(this._gltf.scenes);
  84415. GLTFLoader._AssignIndices(this._gltf.skins);
  84416. GLTFLoader._AssignIndices(this._gltf.textures);
  84417. if (data.bin) {
  84418. var buffers = this._gltf.buffers;
  84419. if (buffers && buffers[0] && !buffers[0].uri) {
  84420. var binaryBuffer = buffers[0];
  84421. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  84422. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  84423. }
  84424. binaryBuffer.loadedData = data.bin;
  84425. }
  84426. else {
  84427. BABYLON.Tools.Warn("Unexpected BIN chunk");
  84428. }
  84429. }
  84430. };
  84431. GLTFLoader.prototype._getMeshes = function () {
  84432. var meshes = new Array();
  84433. // Root mesh is always first.
  84434. meshes.push(this._rootNode.babylonMesh);
  84435. var nodes = this._gltf.nodes;
  84436. if (nodes) {
  84437. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  84438. var node = nodes_1[_i];
  84439. if (node.babylonMesh) {
  84440. meshes.push(node.babylonMesh);
  84441. }
  84442. }
  84443. }
  84444. return meshes;
  84445. };
  84446. GLTFLoader.prototype._getSkeletons = function () {
  84447. var skeletons = new Array();
  84448. var skins = this._gltf.skins;
  84449. if (skins) {
  84450. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  84451. var skin = skins_1[_i];
  84452. if (skin.babylonSkeleton) {
  84453. skeletons.push(skin.babylonSkeleton);
  84454. }
  84455. }
  84456. }
  84457. return skeletons;
  84458. };
  84459. GLTFLoader.prototype._startAnimations = function () {
  84460. var animations = this._gltf.animations;
  84461. if (!animations) {
  84462. return;
  84463. }
  84464. switch (this.animationStartMode) {
  84465. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  84466. // do nothing
  84467. break;
  84468. }
  84469. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  84470. var animation = animations[0];
  84471. for (var _i = 0, _a = animation.targets; _i < _a.length; _i++) {
  84472. var target = _a[_i];
  84473. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  84474. }
  84475. break;
  84476. }
  84477. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  84478. for (var _b = 0, animations_1 = animations; _b < animations_1.length; _b++) {
  84479. var animation = animations_1[_b];
  84480. for (var _c = 0, _d = animation.targets; _c < _d.length; _c++) {
  84481. var target = _d[_c];
  84482. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  84483. }
  84484. }
  84485. break;
  84486. }
  84487. default: {
  84488. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  84489. return;
  84490. }
  84491. }
  84492. };
  84493. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  84494. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  84495. if (!scene) {
  84496. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  84497. }
  84498. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  84499. };
  84500. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  84501. var _this = this;
  84502. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  84503. switch (this.coordinateSystemMode) {
  84504. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  84505. if (!this._babylonScene.useRightHandedSystem) {
  84506. this._rootNode.rotation = [0, 1, 0, 0];
  84507. this._rootNode.scale = [1, 1, -1];
  84508. this._loadTransform(this._rootNode);
  84509. }
  84510. break;
  84511. }
  84512. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  84513. this._babylonScene.useRightHandedSystem = true;
  84514. break;
  84515. }
  84516. default: {
  84517. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  84518. return;
  84519. }
  84520. }
  84521. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  84522. var nodeIndices = scene.nodes;
  84523. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  84524. node.parent = parentNode;
  84525. return true;
  84526. }, this._rootNode);
  84527. if (nodeNames) {
  84528. if (!(nodeNames instanceof Array)) {
  84529. nodeNames = [nodeNames];
  84530. }
  84531. var filteredNodeIndices_1 = new Array();
  84532. this._traverseNodes(context, nodeIndices, function (node) {
  84533. if (nodeNames.indexOf(node.name) !== -1) {
  84534. filteredNodeIndices_1.push(node.index);
  84535. node.parent = _this._rootNode;
  84536. return false;
  84537. }
  84538. return true;
  84539. }, this._rootNode);
  84540. nodeIndices = filteredNodeIndices_1;
  84541. }
  84542. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  84543. var index = nodeIndices_1[_i];
  84544. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84545. if (!node) {
  84546. throw new Error(context + ": Failed to find node " + index);
  84547. }
  84548. this._loadNode("#/nodes/" + index, node);
  84549. }
  84550. // Disable the root mesh until the asset is ready to render.
  84551. this._rootNode.babylonMesh.setEnabled(false);
  84552. };
  84553. GLTFLoader.prototype._loadNode = function (context, node) {
  84554. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  84555. return;
  84556. }
  84557. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  84558. this._loadTransform(node);
  84559. if (node.mesh != null) {
  84560. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  84561. if (!mesh) {
  84562. throw new Error(context + ": Failed to find mesh " + node.mesh);
  84563. }
  84564. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  84565. }
  84566. node.babylonMesh.parent = node.parent.babylonMesh;
  84567. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84568. node.babylonAnimationTargets.push(node.babylonMesh);
  84569. if (node.skin != null) {
  84570. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  84571. if (!skin_1) {
  84572. throw new Error(context + ": Failed to find skin " + node.skin);
  84573. }
  84574. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  84575. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  84576. node.babylonMesh._refreshBoundingInfo(true);
  84577. });
  84578. node.babylonMesh.parent = this._rootNode.babylonMesh;
  84579. node.babylonMesh.position = BABYLON.Vector3.Zero();
  84580. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84581. node.babylonMesh.scaling = BABYLON.Vector3.One();
  84582. }
  84583. if (node.camera != null) {
  84584. // TODO: handle cameras
  84585. }
  84586. if (node.children) {
  84587. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  84588. var index = _a[_i];
  84589. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84590. if (!childNode) {
  84591. throw new Error(context + ": Failed to find child node " + index);
  84592. }
  84593. this._loadNode("#/nodes/" + index, childNode);
  84594. }
  84595. }
  84596. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  84597. };
  84598. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  84599. var _this = this;
  84600. var primitives = mesh.primitives;
  84601. if (!primitives || primitives.length === 0) {
  84602. throw new Error(context + ": Primitives are missing");
  84603. }
  84604. this._createMorphTargets(context, node, mesh);
  84605. this._loadAllVertexDataAsync(context, mesh, function () {
  84606. _this._loadMorphTargets(context, node, mesh);
  84607. var vertexData = new BABYLON.VertexData();
  84608. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  84609. var primitive = primitives_1[_i];
  84610. vertexData.merge(primitive.vertexData);
  84611. }
  84612. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  84613. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  84614. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  84615. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  84616. node.babylonMesh.subMeshes = [];
  84617. var verticesStart = 0;
  84618. var indicesStart = 0;
  84619. for (var index = 0; index < primitives.length; index++) {
  84620. var vertexData_1 = primitives[index].vertexData;
  84621. var verticesCount = vertexData_1.positions.length;
  84622. var indicesCount = vertexData_1.indices.length;
  84623. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  84624. verticesStart += verticesCount;
  84625. indicesStart += indicesCount;
  84626. }
  84627. ;
  84628. });
  84629. if (primitives.length === 1) {
  84630. var primitive = primitives[0];
  84631. if (primitive.material == null) {
  84632. node.babylonMesh.material = this._getDefaultMaterial();
  84633. }
  84634. else {
  84635. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  84636. if (!material) {
  84637. throw new Error(context + ": Failed to find material " + primitive.material);
  84638. }
  84639. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84640. if (isNew) {
  84641. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84642. }
  84643. node.babylonMesh.material = babylonMaterial;
  84644. });
  84645. }
  84646. }
  84647. else {
  84648. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  84649. node.babylonMesh.material = multiMaterial;
  84650. var subMaterials_1 = multiMaterial.subMaterials;
  84651. var _loop_1 = function (index) {
  84652. var primitive = primitives[index];
  84653. if (primitive.material == null) {
  84654. subMaterials_1[index] = this_1._getDefaultMaterial();
  84655. }
  84656. else {
  84657. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  84658. if (!material) {
  84659. throw new Error(context + ": Failed to find material " + primitive.material);
  84660. }
  84661. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84662. if (isNew) {
  84663. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84664. }
  84665. subMaterials_1[index] = babylonMaterial;
  84666. });
  84667. }
  84668. };
  84669. var this_1 = this;
  84670. for (var index = 0; index < primitives.length; index++) {
  84671. _loop_1(index);
  84672. }
  84673. ;
  84674. }
  84675. };
  84676. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  84677. var primitives = mesh.primitives;
  84678. var numRemainingPrimitives = primitives.length;
  84679. var _loop_2 = function (index) {
  84680. var primitive = primitives[index];
  84681. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  84682. primitive.vertexData = vertexData;
  84683. if (--numRemainingPrimitives === 0) {
  84684. onSuccess();
  84685. }
  84686. });
  84687. };
  84688. var this_2 = this;
  84689. for (var index = 0; index < primitives.length; index++) {
  84690. _loop_2(index);
  84691. }
  84692. };
  84693. /**
  84694. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  84695. * @param {ArrayBufferView} data
  84696. * @param {IGLTFAccessor} accessor
  84697. */
  84698. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  84699. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  84700. return data;
  84701. }
  84702. var buffer = data;
  84703. var factor = 1;
  84704. switch (accessor.componentType) {
  84705. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84706. factor = 1 / 255;
  84707. break;
  84708. }
  84709. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84710. factor = 1 / 65535;
  84711. break;
  84712. }
  84713. default: {
  84714. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84715. }
  84716. }
  84717. var result = new Float32Array(accessor.count * 2);
  84718. for (var i = 0; i < result.length; ++i) {
  84719. result[i] = buffer[i] * factor;
  84720. }
  84721. return result;
  84722. };
  84723. /**
  84724. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  84725. * @param {ArrayBufferView} data
  84726. * @param {IGLTFAccessor} accessor
  84727. */
  84728. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  84729. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  84730. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  84731. return data;
  84732. }
  84733. var buffer = data;
  84734. var factor = 1;
  84735. switch (accessor.componentType) {
  84736. case GLTF2.EComponentType.FLOAT: {
  84737. factor = 1;
  84738. break;
  84739. }
  84740. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84741. factor = 1 / 255;
  84742. break;
  84743. }
  84744. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84745. factor = 1 / 65535;
  84746. break;
  84747. }
  84748. default: {
  84749. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84750. }
  84751. }
  84752. var result = new Float32Array(accessor.count * 4);
  84753. if (colorComponentCount === 4) {
  84754. for (var i = 0; i < result.length; ++i) {
  84755. result[i] = buffer[i] * factor;
  84756. }
  84757. }
  84758. else {
  84759. var offset = 0;
  84760. for (var i = 0; i < result.length; ++i) {
  84761. if ((i + 1) % 4 === 0) {
  84762. result[i] = 1;
  84763. }
  84764. else {
  84765. result[i] = buffer[offset++] * factor;
  84766. }
  84767. }
  84768. }
  84769. return result;
  84770. };
  84771. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  84772. var _this = this;
  84773. var attributes = primitive.attributes;
  84774. if (!attributes) {
  84775. throw new Error(context + ": Attributes are missing");
  84776. }
  84777. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  84778. // TODO: handle other primitive modes
  84779. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  84780. }
  84781. var vertexData = new BABYLON.VertexData();
  84782. var numRemainingAttributes = Object.keys(attributes).length;
  84783. var _loop_3 = function (attribute) {
  84784. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  84785. if (!accessor) {
  84786. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84787. }
  84788. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84789. switch (attribute) {
  84790. case "POSITION": {
  84791. vertexData.positions = data;
  84792. break;
  84793. }
  84794. case "NORMAL": {
  84795. vertexData.normals = data;
  84796. break;
  84797. }
  84798. case "TANGENT": {
  84799. vertexData.tangents = data;
  84800. break;
  84801. }
  84802. case "TEXCOORD_0": {
  84803. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84804. break;
  84805. }
  84806. case "TEXCOORD_1": {
  84807. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84808. break;
  84809. }
  84810. case "JOINTS_0": {
  84811. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  84812. break;
  84813. }
  84814. case "WEIGHTS_0": {
  84815. //TODO: need to add support for normalized weights.
  84816. vertexData.matricesWeights = data;
  84817. break;
  84818. }
  84819. case "COLOR_0": {
  84820. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  84821. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  84822. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  84823. mesh.hasVertexAlpha = hasVertexAlpha;
  84824. }
  84825. break;
  84826. }
  84827. default: {
  84828. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  84829. break;
  84830. }
  84831. }
  84832. if (--numRemainingAttributes === 0) {
  84833. if (primitive.indices == null) {
  84834. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  84835. for (var i = 0; i < vertexData.indices.length; i++) {
  84836. vertexData.indices[i] = i;
  84837. }
  84838. onSuccess(vertexData);
  84839. }
  84840. else {
  84841. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  84842. if (!indicesAccessor) {
  84843. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  84844. }
  84845. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  84846. vertexData.indices = data;
  84847. onSuccess(vertexData);
  84848. });
  84849. }
  84850. }
  84851. });
  84852. };
  84853. var this_3 = this;
  84854. for (var attribute in attributes) {
  84855. _loop_3(attribute);
  84856. }
  84857. };
  84858. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  84859. var primitives = mesh.primitives;
  84860. var targets = primitives[0].targets;
  84861. if (!targets) {
  84862. return;
  84863. }
  84864. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  84865. var primitive = primitives_2[_i];
  84866. if (!primitive.targets || primitive.targets.length != targets.length) {
  84867. throw new Error(context + ": All primitives are required to list the same number of targets");
  84868. }
  84869. }
  84870. var morphTargetManager = new BABYLON.MorphTargetManager();
  84871. node.babylonMesh.morphTargetManager = morphTargetManager;
  84872. for (var index = 0; index < targets.length; index++) {
  84873. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  84874. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  84875. }
  84876. };
  84877. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  84878. var morphTargetManager = node.babylonMesh.morphTargetManager;
  84879. if (!morphTargetManager) {
  84880. return;
  84881. }
  84882. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  84883. var numTargets = morphTargetManager.numTargets;
  84884. for (var index = 0; index < numTargets; index++) {
  84885. var vertexData = new BABYLON.VertexData();
  84886. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  84887. var primitive = _a[_i];
  84888. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  84889. }
  84890. if (!vertexData.positions) {
  84891. throw new Error(context + ": Positions are missing");
  84892. }
  84893. var target = morphTargetManager.getTarget(index);
  84894. target.setPositions(vertexData.positions);
  84895. target.setNormals(vertexData.normals);
  84896. target.setTangents(vertexData.tangents);
  84897. }
  84898. });
  84899. };
  84900. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  84901. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  84902. var _loop_4 = function (primitive) {
  84903. var targets = primitive.targets;
  84904. primitive.targetsVertexData = new Array(targets.length);
  84905. var _loop_5 = function (index) {
  84906. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  84907. primitive.targetsVertexData[index] = vertexData;
  84908. if (--numRemainingTargets === 0) {
  84909. onSuccess();
  84910. }
  84911. });
  84912. };
  84913. for (var index = 0; index < targets.length; index++) {
  84914. _loop_5(index);
  84915. }
  84916. };
  84917. var this_4 = this;
  84918. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  84919. var primitive = _a[_i];
  84920. _loop_4(primitive);
  84921. }
  84922. };
  84923. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  84924. var targetVertexData = new BABYLON.VertexData();
  84925. var numRemainingAttributes = Object.keys(attributes).length;
  84926. var _loop_6 = function (attribute) {
  84927. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  84928. if (!accessor) {
  84929. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84930. }
  84931. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84932. // glTF stores morph target information as deltas while babylon.js expects the final data.
  84933. // As a result we have to add the original data to the delta to calculate the final data.
  84934. var values = data;
  84935. switch (attribute) {
  84936. case "POSITION": {
  84937. for (var i = 0; i < values.length; i++) {
  84938. values[i] += vertexData.positions[i];
  84939. }
  84940. targetVertexData.positions = values;
  84941. break;
  84942. }
  84943. case "NORMAL": {
  84944. for (var i = 0; i < values.length; i++) {
  84945. values[i] += vertexData.normals[i];
  84946. }
  84947. targetVertexData.normals = values;
  84948. break;
  84949. }
  84950. case "TANGENT": {
  84951. // Tangent data for morph targets is stored as xyz delta.
  84952. // The vertexData.tangent is stored as xyzw.
  84953. // So we need to skip every fourth vertexData.tangent.
  84954. for (var i = 0, j = 0; i < values.length; i++, j++) {
  84955. values[i] += vertexData.tangents[j];
  84956. if ((i + 1) % 3 == 0) {
  84957. j++;
  84958. }
  84959. }
  84960. targetVertexData.tangents = values;
  84961. break;
  84962. }
  84963. default: {
  84964. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  84965. break;
  84966. }
  84967. }
  84968. if (--numRemainingAttributes === 0) {
  84969. onSuccess(targetVertexData);
  84970. }
  84971. });
  84972. };
  84973. var this_5 = this;
  84974. for (var attribute in attributes) {
  84975. _loop_6(attribute);
  84976. }
  84977. };
  84978. GLTFLoader.prototype._loadTransform = function (node) {
  84979. var position = BABYLON.Vector3.Zero();
  84980. var rotation = BABYLON.Quaternion.Identity();
  84981. var scaling = BABYLON.Vector3.One();
  84982. if (node.matrix) {
  84983. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  84984. matrix.decompose(scaling, rotation, position);
  84985. }
  84986. else {
  84987. if (node.translation)
  84988. position = BABYLON.Vector3.FromArray(node.translation);
  84989. if (node.rotation)
  84990. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  84991. if (node.scale)
  84992. scaling = BABYLON.Vector3.FromArray(node.scale);
  84993. }
  84994. node.babylonMesh.position = position;
  84995. node.babylonMesh.rotationQuaternion = rotation;
  84996. node.babylonMesh.scaling = scaling;
  84997. };
  84998. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  84999. var _this = this;
  85000. if (skin.babylonSkeleton) {
  85001. onSuccess();
  85002. return;
  85003. }
  85004. var skeletonId = "skeleton" + skin.index;
  85005. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  85006. if (skin.inverseBindMatrices == null) {
  85007. this._loadBones(context, skin, null);
  85008. onSuccess();
  85009. }
  85010. else {
  85011. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  85012. if (!accessor) {
  85013. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  85014. }
  85015. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85016. _this._loadBones(context, skin, data);
  85017. onSuccess();
  85018. });
  85019. }
  85020. };
  85021. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  85022. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  85023. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  85024. node.babylonAnimationTargets.push(babylonBone);
  85025. return babylonBone;
  85026. };
  85027. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  85028. var babylonBones = {};
  85029. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  85030. var index = _a[_i];
  85031. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85032. if (!node) {
  85033. throw new Error(context + ": Failed to find joint " + index);
  85034. }
  85035. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  85036. }
  85037. };
  85038. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  85039. var babylonBone = babylonBones[node.index];
  85040. if (babylonBone) {
  85041. return babylonBone;
  85042. }
  85043. var boneIndex = skin.joints.indexOf(node.index);
  85044. var baseMatrix = BABYLON.Matrix.Identity();
  85045. if (inverseBindMatrixData && boneIndex !== -1) {
  85046. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  85047. baseMatrix.invertToRef(baseMatrix);
  85048. }
  85049. var babylonParentBone = null;
  85050. if (node.parent !== this._rootNode) {
  85051. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  85052. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  85053. }
  85054. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  85055. babylonBones[node.index] = babylonBone;
  85056. return babylonBone;
  85057. };
  85058. GLTFLoader.prototype._getNodeMatrix = function (node) {
  85059. return node.matrix ?
  85060. BABYLON.Matrix.FromArray(node.matrix) :
  85061. 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());
  85062. };
  85063. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  85064. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  85065. var index = indices_1[_i];
  85066. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85067. if (!node) {
  85068. throw new Error(context + ": Failed to find node " + index);
  85069. }
  85070. this._traverseNode(context, node, action, parentNode);
  85071. }
  85072. };
  85073. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  85074. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  85075. return;
  85076. }
  85077. if (!action(node, parentNode)) {
  85078. return;
  85079. }
  85080. if (node.children) {
  85081. this._traverseNodes(context, node.children, action, node);
  85082. }
  85083. };
  85084. GLTFLoader.prototype._loadAnimations = function () {
  85085. var animations = this._gltf.animations;
  85086. if (!animations) {
  85087. return;
  85088. }
  85089. for (var index = 0; index < animations.length; index++) {
  85090. var animation = animations[index];
  85091. this._loadAnimation("#/animations/" + index, animation);
  85092. }
  85093. };
  85094. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  85095. animation.targets = [];
  85096. for (var index = 0; index < animation.channels.length; index++) {
  85097. var channel = GLTFLoader._GetProperty(animation.channels, index);
  85098. if (!channel) {
  85099. throw new Error(context + ": Failed to find channel " + index);
  85100. }
  85101. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  85102. if (!sampler) {
  85103. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  85104. }
  85105. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  85106. }
  85107. };
  85108. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  85109. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  85110. if (!targetNode) {
  85111. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  85112. }
  85113. var targetPath;
  85114. var animationType;
  85115. switch (channel.target.path) {
  85116. case "translation": {
  85117. targetPath = "position";
  85118. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85119. break;
  85120. }
  85121. case "rotation": {
  85122. targetPath = "rotationQuaternion";
  85123. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85124. break;
  85125. }
  85126. case "scale": {
  85127. targetPath = "scaling";
  85128. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85129. break;
  85130. }
  85131. case "weights": {
  85132. targetPath = "influence";
  85133. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  85134. break;
  85135. }
  85136. default: {
  85137. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  85138. }
  85139. }
  85140. var inputData;
  85141. var outputData;
  85142. var checkSuccess = function () {
  85143. if (!inputData || !outputData) {
  85144. return;
  85145. }
  85146. var outputBufferOffset = 0;
  85147. var getNextOutputValue;
  85148. switch (targetPath) {
  85149. case "position": {
  85150. getNextOutputValue = function () {
  85151. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85152. outputBufferOffset += 3;
  85153. return value;
  85154. };
  85155. break;
  85156. }
  85157. case "rotationQuaternion": {
  85158. getNextOutputValue = function () {
  85159. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  85160. outputBufferOffset += 4;
  85161. return value;
  85162. };
  85163. break;
  85164. }
  85165. case "scaling": {
  85166. getNextOutputValue = function () {
  85167. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85168. outputBufferOffset += 3;
  85169. return value;
  85170. };
  85171. break;
  85172. }
  85173. case "influence": {
  85174. getNextOutputValue = function () {
  85175. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  85176. var value = new Array(numTargets);
  85177. for (var i = 0; i < numTargets; i++) {
  85178. value[i] = outputData[outputBufferOffset++];
  85179. }
  85180. return value;
  85181. };
  85182. break;
  85183. }
  85184. }
  85185. sampler.interpolation = sampler.interpolation || "LINEAR";
  85186. var getNextKey;
  85187. switch (sampler.interpolation) {
  85188. case "STEP": {
  85189. getNextKey = function (frameIndex) { return ({
  85190. frame: inputData[frameIndex],
  85191. value: getNextOutputValue(),
  85192. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  85193. }); };
  85194. break;
  85195. }
  85196. case "LINEAR": {
  85197. getNextKey = function (frameIndex) { return ({
  85198. frame: inputData[frameIndex],
  85199. value: getNextOutputValue()
  85200. }); };
  85201. break;
  85202. }
  85203. case "CUBICSPLINE": {
  85204. getNextKey = function (frameIndex) { return ({
  85205. frame: inputData[frameIndex],
  85206. inTangent: getNextOutputValue(),
  85207. value: getNextOutputValue(),
  85208. outTangent: getNextOutputValue()
  85209. }); };
  85210. break;
  85211. }
  85212. default: {
  85213. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  85214. }
  85215. }
  85216. ;
  85217. var keys;
  85218. if (inputData.length === 1) {
  85219. var key = getNextKey(0);
  85220. keys = [
  85221. { frame: key.frame, value: key.value },
  85222. { frame: key.frame + 1, value: key.value }
  85223. ];
  85224. }
  85225. else {
  85226. keys = new Array(inputData.length);
  85227. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  85228. keys[frameIndex] = getNextKey(frameIndex);
  85229. }
  85230. }
  85231. if (targetPath === "influence") {
  85232. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  85233. var _loop_7 = function (targetIndex) {
  85234. var morphTarget = morphTargetManager.getTarget(targetIndex);
  85235. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  85236. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85237. babylonAnimation.setKeys(keys.map(function (key) { return ({
  85238. frame: key.frame,
  85239. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  85240. value: key.value[targetIndex],
  85241. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  85242. }); }));
  85243. morphTarget.animations.push(babylonAnimation);
  85244. animation.targets.push(morphTarget);
  85245. };
  85246. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  85247. _loop_7(targetIndex);
  85248. }
  85249. }
  85250. else {
  85251. var animationName = animation.name || "anim" + animation.index;
  85252. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85253. babylonAnimation.setKeys(keys);
  85254. if (targetNode.babylonAnimationTargets) {
  85255. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  85256. var target = _a[_i];
  85257. target.animations.push(babylonAnimation.clone());
  85258. animation.targets.push(target);
  85259. }
  85260. }
  85261. }
  85262. };
  85263. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  85264. if (!inputAccessor) {
  85265. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  85266. }
  85267. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  85268. inputData = data;
  85269. checkSuccess();
  85270. });
  85271. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  85272. if (!outputAccessor) {
  85273. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  85274. }
  85275. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  85276. outputData = data;
  85277. checkSuccess();
  85278. });
  85279. };
  85280. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  85281. var _this = this;
  85282. this._addPendingData(buffer);
  85283. if (buffer.loadedData) {
  85284. onSuccess(buffer.loadedData);
  85285. this._removePendingData(buffer);
  85286. }
  85287. else if (buffer.loadedObservable) {
  85288. buffer.loadedObservable.add(function (buffer) {
  85289. onSuccess(buffer.loadedData);
  85290. _this._removePendingData(buffer);
  85291. });
  85292. }
  85293. else {
  85294. if (!buffer.uri) {
  85295. throw new Error(context + ": Uri is missing");
  85296. }
  85297. buffer.loadedObservable = new BABYLON.Observable();
  85298. buffer.loadedObservable.add(function (buffer) {
  85299. onSuccess(buffer.loadedData);
  85300. _this._removePendingData(buffer);
  85301. });
  85302. this._loadUriAsync(context, buffer.uri, function (data) {
  85303. buffer.loadedData = data;
  85304. buffer.loadedObservable.notifyObservers(buffer);
  85305. buffer.loadedObservable = undefined;
  85306. });
  85307. }
  85308. };
  85309. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  85310. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  85311. if (!buffer) {
  85312. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  85313. }
  85314. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  85315. var data;
  85316. try {
  85317. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  85318. }
  85319. catch (e) {
  85320. throw new Error(context + ": " + e.message);
  85321. }
  85322. onSuccess(data);
  85323. });
  85324. };
  85325. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  85326. var _this = this;
  85327. if (accessor.sparse) {
  85328. throw new Error(context + ": Sparse accessors are not currently supported");
  85329. }
  85330. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  85331. if (!bufferView) {
  85332. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  85333. }
  85334. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  85335. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  85336. var data;
  85337. var byteOffset = accessor.byteOffset || 0;
  85338. var byteStride = bufferView.byteStride;
  85339. if (byteStride === 0) {
  85340. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  85341. }
  85342. try {
  85343. switch (accessor.componentType) {
  85344. case GLTF2.EComponentType.BYTE: {
  85345. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85346. break;
  85347. }
  85348. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85349. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85350. break;
  85351. }
  85352. case GLTF2.EComponentType.SHORT: {
  85353. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85354. break;
  85355. }
  85356. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85357. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85358. break;
  85359. }
  85360. case GLTF2.EComponentType.UNSIGNED_INT: {
  85361. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85362. break;
  85363. }
  85364. case GLTF2.EComponentType.FLOAT: {
  85365. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85366. break;
  85367. }
  85368. default: {
  85369. throw new Error(context + ": Invalid component type " + accessor.componentType);
  85370. }
  85371. }
  85372. }
  85373. catch (e) {
  85374. throw new Error(context + ": " + e);
  85375. }
  85376. onSuccess(data);
  85377. });
  85378. };
  85379. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  85380. byteOffset += data.byteOffset;
  85381. var targetLength = count * numComponents;
  85382. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  85383. return new typedArray(data.buffer, byteOffset, targetLength);
  85384. }
  85385. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  85386. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  85387. var targetBuffer = new typedArray(targetLength);
  85388. var sourceIndex = 0;
  85389. var targetIndex = 0;
  85390. while (targetIndex < targetLength) {
  85391. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  85392. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  85393. targetIndex++;
  85394. }
  85395. sourceIndex += elementStride;
  85396. }
  85397. return targetBuffer;
  85398. };
  85399. GLTFLoader.prototype._addPendingData = function (data) {
  85400. if (!this._renderReady) {
  85401. this._renderPendingCount++;
  85402. }
  85403. this._addLoaderPendingData(data);
  85404. };
  85405. GLTFLoader.prototype._removePendingData = function (data) {
  85406. var _this = this;
  85407. if (!this._renderReady) {
  85408. if (--this._renderPendingCount === 0) {
  85409. this._addLoaderPendingData(this);
  85410. this._compileMaterialsAsync(function () {
  85411. _this._compileShadowGeneratorsAsync(function () {
  85412. _this._removeLoaderPendingData(_this);
  85413. _this._renderReady = true;
  85414. _this._onRenderReady();
  85415. });
  85416. });
  85417. }
  85418. }
  85419. this._removeLoaderPendingData(data);
  85420. };
  85421. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  85422. this._loaderPendingCount++;
  85423. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85424. var tracker = _a[_i];
  85425. tracker._addPendingData(data);
  85426. }
  85427. };
  85428. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  85429. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85430. var tracker = _a[_i];
  85431. tracker._removePendingData(data);
  85432. }
  85433. if (--this._loaderPendingCount === 0) {
  85434. this._onComplete();
  85435. }
  85436. };
  85437. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  85438. var _this = this;
  85439. var tracker = new GLTFLoaderTracker(function () {
  85440. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  85441. onComplete();
  85442. });
  85443. this._loaderTrackers.push(tracker);
  85444. this._addLoaderPendingData(tracker);
  85445. action();
  85446. this._removeLoaderPendingData(tracker);
  85447. };
  85448. GLTFLoader.prototype._getDefaultMaterial = function () {
  85449. if (!this._defaultMaterial) {
  85450. var id = "__gltf_default";
  85451. var material = this._babylonScene.getMaterialByName(id);
  85452. if (!material) {
  85453. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  85454. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85455. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85456. material.metallic = 1;
  85457. material.roughness = 1;
  85458. }
  85459. this._defaultMaterial = material;
  85460. }
  85461. return this._defaultMaterial;
  85462. };
  85463. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  85464. var babylonMaterial = material.babylonMaterial;
  85465. // Ensure metallic workflow
  85466. babylonMaterial.metallic = 1;
  85467. babylonMaterial.roughness = 1;
  85468. var properties = material.pbrMetallicRoughness;
  85469. if (!properties) {
  85470. return;
  85471. }
  85472. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  85473. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  85474. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  85475. if (properties.baseColorTexture) {
  85476. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  85477. if (!texture) {
  85478. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  85479. }
  85480. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  85481. }
  85482. if (properties.metallicRoughnessTexture) {
  85483. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  85484. if (!texture) {
  85485. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  85486. }
  85487. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  85488. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  85489. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  85490. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  85491. }
  85492. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  85493. };
  85494. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  85495. if (material.babylonMaterial) {
  85496. assign(material.babylonMaterial, false);
  85497. return;
  85498. }
  85499. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  85500. return;
  85501. }
  85502. this._createPbrMaterial(material);
  85503. this._loadMaterialBaseProperties(context, material);
  85504. this._loadMaterialMetallicRoughnessProperties(context, material);
  85505. assign(material.babylonMaterial, true);
  85506. };
  85507. GLTFLoader.prototype._createPbrMaterial = function (material) {
  85508. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  85509. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85510. material.babylonMaterial = babylonMaterial;
  85511. };
  85512. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  85513. var babylonMaterial = material.babylonMaterial;
  85514. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  85515. if (material.doubleSided) {
  85516. babylonMaterial.backFaceCulling = false;
  85517. babylonMaterial.twoSidedLighting = true;
  85518. }
  85519. if (material.normalTexture) {
  85520. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  85521. if (!texture) {
  85522. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  85523. }
  85524. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  85525. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  85526. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  85527. if (material.normalTexture.scale != null) {
  85528. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  85529. }
  85530. }
  85531. if (material.occlusionTexture) {
  85532. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  85533. if (!texture) {
  85534. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  85535. }
  85536. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  85537. babylonMaterial.useAmbientInGrayScale = true;
  85538. if (material.occlusionTexture.strength != null) {
  85539. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  85540. }
  85541. }
  85542. if (material.emissiveTexture) {
  85543. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  85544. if (!texture) {
  85545. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  85546. }
  85547. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  85548. }
  85549. };
  85550. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  85551. var babylonMaterial = material.babylonMaterial;
  85552. var alphaMode = material.alphaMode || "OPAQUE";
  85553. switch (alphaMode) {
  85554. case "OPAQUE": {
  85555. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85556. break;
  85557. }
  85558. case "MASK": {
  85559. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  85560. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  85561. if (colorFactor) {
  85562. if (colorFactor[3] == 0) {
  85563. babylonMaterial.alphaCutOff = 1;
  85564. }
  85565. else {
  85566. babylonMaterial.alphaCutOff /= colorFactor[3];
  85567. }
  85568. }
  85569. if (babylonMaterial.albedoTexture) {
  85570. babylonMaterial.albedoTexture.hasAlpha = true;
  85571. }
  85572. break;
  85573. }
  85574. case "BLEND": {
  85575. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  85576. if (colorFactor) {
  85577. babylonMaterial.alpha = colorFactor[3];
  85578. }
  85579. if (babylonMaterial.albedoTexture) {
  85580. babylonMaterial.albedoTexture.hasAlpha = true;
  85581. babylonMaterial.useAlphaFromAlbedoTexture = true;
  85582. }
  85583. break;
  85584. }
  85585. default: {
  85586. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  85587. }
  85588. }
  85589. };
  85590. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  85591. var _this = this;
  85592. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  85593. if (!sampler) {
  85594. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  85595. }
  85596. this._loadSampler("#/samplers/" + sampler.index, sampler);
  85597. this._addPendingData(texture);
  85598. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  85599. _this._tryCatchOnError(function () {
  85600. _this._removePendingData(texture);
  85601. });
  85602. }, function (message) {
  85603. _this._tryCatchOnError(function () {
  85604. throw new Error(context + ": " + message);
  85605. });
  85606. });
  85607. if (texture.url) {
  85608. babylonTexture.updateURL(texture.url);
  85609. }
  85610. else if (texture.dataReadyObservable) {
  85611. texture.dataReadyObservable.add(function (texture) {
  85612. babylonTexture.updateURL(texture.url);
  85613. });
  85614. }
  85615. else {
  85616. texture.dataReadyObservable = new BABYLON.Observable();
  85617. texture.dataReadyObservable.add(function (texture) {
  85618. babylonTexture.updateURL(texture.url);
  85619. });
  85620. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  85621. if (!image_1) {
  85622. throw new Error(context + ": Failed to find source " + texture.source);
  85623. }
  85624. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  85625. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  85626. texture.dataReadyObservable.notifyObservers(texture);
  85627. texture.dataReadyObservable = undefined;
  85628. });
  85629. }
  85630. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  85631. babylonTexture.wrapU = sampler.wrapU;
  85632. babylonTexture.wrapV = sampler.wrapV;
  85633. babylonTexture.name = texture.name || "texture" + texture.index;
  85634. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  85635. return babylonTexture;
  85636. };
  85637. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  85638. if (sampler.noMipMaps != undefined) {
  85639. return;
  85640. }
  85641. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  85642. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  85643. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  85644. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  85645. };
  85646. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  85647. if (image.uri) {
  85648. this._loadUriAsync(context, image.uri, onSuccess);
  85649. }
  85650. else {
  85651. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  85652. if (!bufferView) {
  85653. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  85654. }
  85655. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  85656. }
  85657. };
  85658. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  85659. var _this = this;
  85660. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  85661. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  85662. return;
  85663. }
  85664. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  85665. throw new Error(context + ": Uri '" + uri + "' is invalid");
  85666. }
  85667. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  85668. _this._tryCatchOnError(function () {
  85669. onSuccess(new Uint8Array(data));
  85670. });
  85671. }, function (event) {
  85672. _this._tryCatchOnError(function () {
  85673. if (request && !_this._renderReady) {
  85674. request._lengthComputable = event.lengthComputable;
  85675. request._loaded = event.loaded;
  85676. request._total = event.total;
  85677. _this._onProgress();
  85678. }
  85679. });
  85680. }, this._babylonScene.database, true, function (request, exception) {
  85681. _this._tryCatchOnError(function () {
  85682. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  85683. });
  85684. });
  85685. this._requests.push(request);
  85686. request.onCompleteObservable.add(function () {
  85687. _this._requests.splice(_this._requests.indexOf(request), 1);
  85688. });
  85689. };
  85690. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  85691. if (this._disposed) {
  85692. return;
  85693. }
  85694. try {
  85695. handler();
  85696. }
  85697. catch (e) {
  85698. BABYLON.Tools.Error("glTF Loader: " + e.message);
  85699. if (this._errorCallback) {
  85700. this._errorCallback(e.message, e);
  85701. }
  85702. this.dispose();
  85703. }
  85704. };
  85705. GLTFLoader._AssignIndices = function (array) {
  85706. if (array) {
  85707. for (var index = 0; index < array.length; index++) {
  85708. array[index].index = index;
  85709. }
  85710. }
  85711. };
  85712. GLTFLoader._GetProperty = function (array, index) {
  85713. if (!array || index == undefined || !array[index]) {
  85714. return null;
  85715. }
  85716. return array[index];
  85717. };
  85718. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  85719. // Set defaults if undefined
  85720. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  85721. switch (mode) {
  85722. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  85723. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  85724. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85725. default:
  85726. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  85727. return BABYLON.Texture.WRAP_ADDRESSMODE;
  85728. }
  85729. };
  85730. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  85731. // Set defaults if undefined
  85732. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  85733. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  85734. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  85735. switch (minFilter) {
  85736. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  85737. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  85738. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  85739. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  85740. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  85741. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85742. default:
  85743. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85744. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85745. }
  85746. }
  85747. else {
  85748. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  85749. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  85750. }
  85751. switch (minFilter) {
  85752. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  85753. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  85754. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85755. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  85756. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  85757. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  85758. default:
  85759. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85760. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85761. }
  85762. }
  85763. };
  85764. GLTFLoader._GetNumComponents = function (context, type) {
  85765. switch (type) {
  85766. case "SCALAR": return 1;
  85767. case "VEC2": return 2;
  85768. case "VEC3": return 3;
  85769. case "VEC4": return 4;
  85770. case "MAT2": return 4;
  85771. case "MAT3": return 9;
  85772. case "MAT4": return 16;
  85773. }
  85774. throw new Error(context + ": Invalid type " + type);
  85775. };
  85776. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  85777. var _this = this;
  85778. if (this.useClipPlane) {
  85779. babylonMaterial.forceCompilation(babylonMesh, function () {
  85780. babylonMaterial.forceCompilation(babylonMesh, function () {
  85781. _this._tryCatchOnError(onSuccess);
  85782. }, { clipPlane: true });
  85783. });
  85784. }
  85785. else {
  85786. babylonMaterial.forceCompilation(babylonMesh, function () {
  85787. _this._tryCatchOnError(onSuccess);
  85788. });
  85789. }
  85790. };
  85791. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  85792. if (!this.compileMaterials || !this._gltf.materials) {
  85793. onSuccess();
  85794. return;
  85795. }
  85796. var meshes = this._getMeshes();
  85797. var remaining = 0;
  85798. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  85799. var mesh = meshes_1[_i];
  85800. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85801. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  85802. var subMaterial = _b[_a];
  85803. if (subMaterial) {
  85804. remaining++;
  85805. }
  85806. }
  85807. }
  85808. else if (mesh.material) {
  85809. remaining++;
  85810. }
  85811. }
  85812. if (remaining === 0) {
  85813. onSuccess();
  85814. return;
  85815. }
  85816. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  85817. var mesh = meshes_2[_c];
  85818. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85819. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  85820. var subMaterial = _e[_d];
  85821. if (subMaterial) {
  85822. this._compileMaterialAsync(subMaterial, mesh, function () {
  85823. if (--remaining === 0) {
  85824. onSuccess();
  85825. }
  85826. });
  85827. }
  85828. }
  85829. }
  85830. else if (mesh.material) {
  85831. this._compileMaterialAsync(mesh.material, mesh, function () {
  85832. if (--remaining === 0) {
  85833. onSuccess();
  85834. }
  85835. });
  85836. }
  85837. }
  85838. };
  85839. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  85840. var _this = this;
  85841. if (!this.compileShadowGenerators) {
  85842. onSuccess();
  85843. return;
  85844. }
  85845. var lights = this._babylonScene.lights;
  85846. var remaining = 0;
  85847. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  85848. var light = lights_1[_i];
  85849. var generator = light.getShadowGenerator();
  85850. if (generator) {
  85851. remaining++;
  85852. }
  85853. }
  85854. if (remaining === 0) {
  85855. onSuccess();
  85856. return;
  85857. }
  85858. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  85859. var light = lights_2[_a];
  85860. var generator = light.getShadowGenerator();
  85861. if (generator) {
  85862. generator.forceCompilation(function () {
  85863. if (--remaining === 0) {
  85864. _this._tryCatchOnError(onSuccess);
  85865. }
  85866. });
  85867. }
  85868. }
  85869. };
  85870. GLTFLoader.prototype._abortRequests = function () {
  85871. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  85872. var request = _a[_i];
  85873. request.abort();
  85874. }
  85875. this._requests.length = 0;
  85876. };
  85877. GLTFLoader.prototype._releaseResources = function () {
  85878. if (this._gltf.textures) {
  85879. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  85880. var texture = _a[_i];
  85881. if (texture.url) {
  85882. URL.revokeObjectURL(texture.url);
  85883. texture.url = undefined;
  85884. }
  85885. }
  85886. }
  85887. };
  85888. GLTFLoader.Extensions = {};
  85889. return GLTFLoader;
  85890. }());
  85891. GLTF2.GLTFLoader = GLTFLoader;
  85892. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  85893. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85894. })(BABYLON || (BABYLON = {}));
  85895. //# sourceMappingURL=babylon.glTFLoader.js.map
  85896. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85897. var BABYLON;
  85898. (function (BABYLON) {
  85899. var GLTF2;
  85900. (function (GLTF2) {
  85901. /**
  85902. * Utils functions for GLTF
  85903. */
  85904. var GLTFUtils = /** @class */ (function () {
  85905. function GLTFUtils() {
  85906. }
  85907. /**
  85908. * If the uri is a base64 string
  85909. * @param uri: the uri to test
  85910. */
  85911. GLTFUtils.IsBase64 = function (uri) {
  85912. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  85913. };
  85914. /**
  85915. * Decode the base64 uri
  85916. * @param uri: the uri to decode
  85917. */
  85918. GLTFUtils.DecodeBase64 = function (uri) {
  85919. var decodedString = atob(uri.split(",")[1]);
  85920. var bufferLength = decodedString.length;
  85921. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  85922. for (var i = 0; i < bufferLength; i++) {
  85923. bufferView[i] = decodedString.charCodeAt(i);
  85924. }
  85925. return bufferView.buffer;
  85926. };
  85927. GLTFUtils.ValidateUri = function (uri) {
  85928. return (uri.indexOf("..") === -1);
  85929. };
  85930. return GLTFUtils;
  85931. }());
  85932. GLTF2.GLTFUtils = GLTFUtils;
  85933. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85934. })(BABYLON || (BABYLON = {}));
  85935. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  85936. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85937. var BABYLON;
  85938. (function (BABYLON) {
  85939. var GLTF2;
  85940. (function (GLTF2) {
  85941. var GLTFLoaderExtension = /** @class */ (function () {
  85942. function GLTFLoaderExtension() {
  85943. this.enabled = true;
  85944. }
  85945. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  85946. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  85947. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  85948. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  85949. var _this = this;
  85950. if (!property.extensions) {
  85951. return false;
  85952. }
  85953. var extension = property.extensions[this.name];
  85954. if (!extension) {
  85955. return false;
  85956. }
  85957. // Clear out the extension before executing the action to avoid recursing into the same property.
  85958. property.extensions[this.name] = undefined;
  85959. action(context + "extensions/" + this.name, extension, function () {
  85960. // Restore the extension after completing the action.
  85961. property.extensions[_this.name] = extension;
  85962. });
  85963. return true;
  85964. };
  85965. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  85966. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  85967. };
  85968. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  85969. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  85970. };
  85971. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  85972. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  85973. };
  85974. GLTFLoaderExtension._ApplyExtensions = function (action) {
  85975. var extensions = GLTFLoaderExtension._Extensions;
  85976. if (!extensions) {
  85977. return false;
  85978. }
  85979. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  85980. var extension = extensions_1[_i];
  85981. if (extension.enabled && action(extension)) {
  85982. return true;
  85983. }
  85984. }
  85985. return false;
  85986. };
  85987. //
  85988. // Utilities
  85989. //
  85990. GLTFLoaderExtension._Extensions = [];
  85991. return GLTFLoaderExtension;
  85992. }());
  85993. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  85994. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  85995. })(BABYLON || (BABYLON = {}));
  85996. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  85997. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  85998. var BABYLON;
  85999. (function (BABYLON) {
  86000. var GLTF2;
  86001. (function (GLTF2) {
  86002. var Extensions;
  86003. (function (Extensions) {
  86004. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  86005. var MSFTLOD = /** @class */ (function (_super) {
  86006. __extends(MSFTLOD, _super);
  86007. function MSFTLOD() {
  86008. var _this = _super !== null && _super.apply(this, arguments) || this;
  86009. /**
  86010. * Specify the minimal delay between LODs in ms (default = 250)
  86011. */
  86012. _this.Delay = 250;
  86013. return _this;
  86014. }
  86015. Object.defineProperty(MSFTLOD.prototype, "name", {
  86016. get: function () {
  86017. return "MSFT_lod";
  86018. },
  86019. enumerable: true,
  86020. configurable: true
  86021. });
  86022. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  86023. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86024. for (var i = extension.ids.length - 1; i >= 0; i--) {
  86025. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  86026. if (!lodNode) {
  86027. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  86028. }
  86029. loader._traverseNode(context, lodNode, action, parentNode);
  86030. }
  86031. loader._traverseNode(context, node, action, parentNode);
  86032. onComplete();
  86033. });
  86034. };
  86035. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  86036. var _this = this;
  86037. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86038. var nodes = [node];
  86039. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86040. var index = _a[_i];
  86041. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  86042. if (!lodNode) {
  86043. throw new Error(context + ": Failed to find node " + index);
  86044. }
  86045. nodes.push(lodNode);
  86046. }
  86047. loader._addLoaderPendingData(node);
  86048. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  86049. loader._removeLoaderPendingData(node);
  86050. onComplete();
  86051. });
  86052. });
  86053. };
  86054. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  86055. var _this = this;
  86056. loader._whenAction(function () {
  86057. loader._loadNode(context, nodes[index]);
  86058. }, function () {
  86059. if (index !== nodes.length - 1) {
  86060. var previousNode = nodes[index + 1];
  86061. previousNode.babylonMesh.setEnabled(false);
  86062. }
  86063. if (index === 0) {
  86064. onComplete();
  86065. return;
  86066. }
  86067. setTimeout(function () {
  86068. loader._tryCatchOnError(function () {
  86069. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  86070. });
  86071. }, _this.Delay);
  86072. });
  86073. };
  86074. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  86075. var _this = this;
  86076. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86077. var materials = [material];
  86078. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86079. var index = _a[_i];
  86080. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  86081. if (!lodMaterial) {
  86082. throw new Error(context + ": Failed to find material " + index);
  86083. }
  86084. materials.push(lodMaterial);
  86085. }
  86086. loader._addLoaderPendingData(material);
  86087. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  86088. loader._removeLoaderPendingData(material);
  86089. onComplete();
  86090. });
  86091. });
  86092. };
  86093. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  86094. var _this = this;
  86095. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  86096. if (index === materials.length - 1) {
  86097. assign(babylonMaterial, isNew);
  86098. // Load the next LOD when the loader is ready to render.
  86099. loader._executeWhenRenderReady(function () {
  86100. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86101. });
  86102. }
  86103. else {
  86104. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  86105. assign(babylonMaterial, isNew);
  86106. if (index === 0) {
  86107. onComplete();
  86108. }
  86109. else {
  86110. setTimeout(function () {
  86111. loader._tryCatchOnError(function () {
  86112. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86113. });
  86114. }, _this.Delay);
  86115. }
  86116. });
  86117. }
  86118. });
  86119. };
  86120. return MSFTLOD;
  86121. }(GLTF2.GLTFLoaderExtension));
  86122. Extensions.MSFTLOD = MSFTLOD;
  86123. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  86124. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86125. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86126. })(BABYLON || (BABYLON = {}));
  86127. //# sourceMappingURL=MSFT_lod.js.map
  86128. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86129. var BABYLON;
  86130. (function (BABYLON) {
  86131. var GLTF2;
  86132. (function (GLTF2) {
  86133. var Extensions;
  86134. (function (Extensions) {
  86135. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  86136. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  86137. function KHRMaterialsPbrSpecularGlossiness() {
  86138. return _super !== null && _super.apply(this, arguments) || this;
  86139. }
  86140. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  86141. get: function () {
  86142. return "KHR_materials_pbrSpecularGlossiness";
  86143. },
  86144. enumerable: true,
  86145. configurable: true
  86146. });
  86147. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  86148. var _this = this;
  86149. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86150. loader._createPbrMaterial(material);
  86151. loader._loadMaterialBaseProperties(context, material);
  86152. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  86153. assign(material.babylonMaterial, true);
  86154. onComplete();
  86155. });
  86156. };
  86157. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  86158. var babylonMaterial = material.babylonMaterial;
  86159. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  86160. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  86161. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  86162. if (properties.diffuseTexture) {
  86163. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  86164. if (!texture) {
  86165. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  86166. }
  86167. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  86168. }
  86169. if (properties.specularGlossinessTexture) {
  86170. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  86171. if (!texture) {
  86172. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  86173. }
  86174. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  86175. babylonMaterial.reflectivityTexture.hasAlpha = true;
  86176. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  86177. }
  86178. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  86179. };
  86180. return KHRMaterialsPbrSpecularGlossiness;
  86181. }(GLTF2.GLTFLoaderExtension));
  86182. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  86183. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  86184. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86185. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86186. })(BABYLON || (BABYLON = {}));
  86187. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  86188. (function universalModuleDefinition(root, factory) {
  86189. var f = factory();
  86190. if (root && root["BABYLON"]) {
  86191. return;
  86192. }
  86193. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  86194. globalObject["BABYLON"] = f;
  86195. if(typeof exports === 'object' && typeof module === 'object')
  86196. module.exports = f;
  86197. else if(typeof define === 'function' && define.amd)
  86198. define(["BABYLON"], factory);
  86199. else if(typeof exports === 'object')
  86200. exports["BABYLON"] = f;
  86201. else {
  86202. root["BABYLON"] = f;
  86203. }
  86204. })(this, function() {
  86205. return BABYLON;
  86206. });